23 Commits

Author SHA1 Message Date
d9d80c4eee Merge pull request 'Fix #77: Add a "force import from foundry" context button' (#80) from ai/issue-77 into master
Some checks failed
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Has been cancelled
Reviewed-on: #80
2026-10-15 19:31:33 +00:00
4eda4a9d21 Merge branch 'master' into ai/issue-77
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 19:31:26 +00:00
b64d1e3089 Merge pull request 'Fix #74: Foundry's icons are not available: its bridge is not set up, or it cannot be reached right now.' (#82) from ai/issue-74 into master
Some checks failed
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Has been cancelled
Reviewed-on: #82
2026-10-15 19:31:20 +00:00
fefb1eba6e Merge branch 'master' into ai/issue-74
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 19:31:14 +00:00
Gitea OpenCode Agent
06144e1623 Fix issue #74: Foundry's icons are not available: its bridge is not set up, or it cannot be reached right now.
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 19:24:18 +00:00
Gitea OpenCode Agent
f928f13544 Fix issue #77: Add a "force import from foundry" context button
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 18:16:47 +00:00
a8a1e0ca41 Merge pull request 'Fix #72: Link actor with a discord user' (#78) from ai/issue-72 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 1m10s
Reviewed-on: #78
2026-10-15 17:08:10 +00:00
fa82c933d6 Merge branch 'master' into ai/issue-72
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 17:08:02 +00:00
Gitea OpenCode Agent
299380d143 Fix issue #72: Link actor with a discord user
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 17:06:25 +00:00
6df7d57376 Merge pull request 'Fix #71: Nuxt error with colors' (#76) from ai/issue-71 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 51s
Reviewed-on: #76
2026-10-15 16:45:44 +00:00
a8047e2814 Merge branch 'master' into ai/issue-71
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 16:45:39 +00:00
Gitea OpenCode Agent
37e6e44612 Fix issue #71: Nuxt error with colors
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 16:44:08 +00:00
b0cc98a452 Merge pull request 'Fix #67: Don't show all items on the items sidebar' (#75) from ai/issue-67 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 1m27s
Reviewed-on: #75
2026-10-15 16:40:39 +00:00
d35216c859 Merge branch 'master' into ai/issue-67
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 16:40:30 +00:00
Gitea OpenCode Agent
495e528124 Fix issue #67: Don't show all items on the items sidebar
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 16:40:15 +00:00
Gitea OpenCode Agent
dd4c9535d3 Fix issue #65: Item selecting icon
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 1m7s
2026-10-15 18:08:27 +02:00
0caacf434f Merge pull request 'Fix #64: More modifications to the character sheet' (#70) from ai/issue-64 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 1m5s
Reviewed-on: #70
2026-10-15 15:19:53 +00:00
d779d939f9 Merge branch 'master' into ai/issue-64
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 15:19:46 +00:00
eeaab7a910 Merge pull request 'Fix #63: Item modifications' (#69) from ai/issue-63 into master
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 51s
Reviewed-on: #69
2026-10-15 15:17:41 +00:00
f9caff3100 Merge branch 'master' into ai/issue-63
All checks were successful
Test / test (push) Successful in 2s
2026-10-15 15:17:34 +00:00
Gitea OpenCode Agent
0567096588 Fix issue #61: Fix tests
Some checks failed
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Has been cancelled
2026-10-15 17:16:48 +02:00
Gitea OpenCode Agent
8418b5c254 Fix issue #64: More modifications to the character sheet
Some checks failed
Test / test (push) Failing after 2s
2026-10-15 15:01:35 +00:00
Gitea OpenCode Agent
09e9010729 Fix issue #63: Item modifications
Some checks failed
Test / test (push) Failing after 2s
2026-10-15 14:31:00 +00:00
43 changed files with 2768 additions and 285 deletions

View File

@@ -85,7 +85,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user
- `Campaign` — `name*`, `createdBy*`→User, `description`, `color`, `settings`, `foundryWorldId`/`foundryWorldTitle`/`foundrySystem`, `foundrySyncTokenHash` (`select: false`), `discordGuildId` - `Campaign` — `name*`, `createdBy*`→User, `description`, `color`, `settings`, `foundryWorldId`/`foundryWorldTitle`/`foundrySystem`, `foundrySyncTokenHash` (`select: false`), `discordGuildId`
- `Note` — `title`, `content` (markdown source), `campaign*`, `folder` (null = root), `color` - `Note` — `title`, `content` (markdown source), `campaign*`, `folder` (null = root), `color`
- `Folder` — `name*`, `campaign*`, `parentFolder` (null = root, self-ref), `color` - `Folder` — `name*`, `campaign*`, `parentFolder` (null = root, self-ref), `color`
- `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), plus free-form sheet fields (`type`, `species`, `className`, `level`, `abilityScores`, `armorClass`, `speed`, `proficiencies`, `traits`, `spells`, `image`) and `inventory[{name,quantity,weight}]` (flattened Foundry items, **not** `Item` docs) - `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), `discordUserId` (the Discord player holding the character, unique per campaign — set only by `routes/discord.js`), plus free-form sheet fields (`type`, `species`, `className`, `level`, `abilityScores`, `armorClass`, `speed`, `proficiencies`, `traits`, `spells`, `image`) and `inventory[{name,quantity,weight}]` (flattened Foundry items, **not** `Item` docs)
- `Item` — `name*`, `campaign*`, `foundryItemId` (unique per campaign), `foundryNames`, `category`, `rarity`, `quantity`, `weight`, `properties`, `description` - `Item` — `name*`, `campaign*`, `foundryItemId` (unique per campaign), `foundryNames`, `category`, `rarity`, `quantity`, `weight`, `properties`, `description`
- `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`), `gridSize`/`offsetX`/`offsetY`/`scale` (image px), `pins[{note→Note, x, y}]` (addressed by the pin's own `_id`), `tokens[{actor→Actor, x, y}]` (the centre of the grid cell the token stands in, also addressed by its own `_id`) - `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`), `gridSize`/`offsetX`/`offsetY`/`scale` (image px), `pins[{note→Note, x, y}]` (addressed by the pin's own `_id`), `tokens[{actor→Actor, x, y}]` (the centre of the grid cell the token stands in, also addressed by its own `_id`)
- `ServiceLinkRequest` — the pending/completed service pairings of §4; `DiscordGuildLink` maps a Discord guild to the Dragonroll user who claimed it - `ServiceLinkRequest` — the pending/completed service pairings of §4; `DiscordGuildLink` maps a Discord guild to the Dragonroll user who claimed it
@@ -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` - `actor` — `list`, `create`, `update` (partial, ownership checked), `upload-image?actor=` (multipart), `delete`
- `item` — `list`, `create`, `update` (partial), `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}`) - `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`; `POST /import` (`{campaign, kind: 'actors'|'items'}`, the sidebar's "force import from Foundry") pulls that world's whole list off the bridge through the sync's writers, so rows the campaign already has are written over, and answers `{imported, updated}`; `/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) ## 4. Service integrations (Foundry, Discord, Obsidian)
@@ -117,11 +117,11 @@ the JWT guard; CORS opened for it): `snapshot` (actors + world items, `fullSync`
`item-snapshot`, `item-delete`, `characters`, `items`, `status`, `map` / `map-item`, `delete`. Rules: `item-snapshot`, `item-delete`, `characters`, `items`, `status`, `map` / `map-item`, `delete`. Rules:
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index); a Foundry document carrying the `dragonroll-foundry.actorId` / `.itemId` flag adopts the matching Dragonroll row. - **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. - **Only the world's item directory reaches the item list** (Syndria98/dragonroll#67) — `snapshotItemSources` reads `body.items` (`game.items`) alone; gear embedded in a character is that actor's `inventory` (see the `Actor` model), not an `Item`. A world item still folds into a hand-made or renamed row it matches by name (`foundryNames`), so a 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. - **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. - **`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`). - **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. - `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge. Its one write, `POST /import`, pulls the bridge's actors or world items into the campaign through the same writers as a sync push.
## 5. Frontend ## 5. Frontend

View File

@@ -22,6 +22,17 @@ const ActorSchema = new Schema({
}, },
armorClass: { type: Number, min: 0, default: 10 }, armorClass: { type: Number, min: 0, default: 10 },
speed: { type: Number, min: 0, default: 30 }, speed: { type: Number, min: 0, default: 30 },
// The two pools the sheet draws as bars under the portrait (Syndria98/dragonroll#64): the bar
// fills `current` of `max`, so both travel together. `current` is kept below `max` by whoever
// writes them (routes/actor.js), the same way the sheet clamps the bar.
hitPoints: {
current: { type: Number, min: 0, default: 10 },
max: { type: Number, min: 0, default: 10 }
},
hitDice: {
current: { type: Number, min: 0, default: 1 },
max: { type: Number, min: 0, default: 1 }
},
proficiencies: { type: String, default: '' }, proficiencies: { type: String, default: '' },
inventory: [{ inventory: [{
name: { type: String, trim: true, default: '' }, name: { type: String, trim: true, default: '' },
@@ -43,6 +54,10 @@ const ActorSchema = new Schema({
default: null default: null
}, },
foundryActorId: { type: String }, foundryActorId: { type: String },
// The Discord player this character belongs to (Syndria98/dragonroll#72): each player
// of the server a campaign is linked to holds one character of it. Only
// routes/discord.js writes it, so the campaign keeps owning it whichever guild claimed it.
discordUserId: { type: String, default: null },
date: { type: Date, default: Date.now } date: { type: Date, default: Date.now }
}); });
@@ -51,4 +66,10 @@ ActorSchema.index(
{ unique: true, partialFilterExpression: { foundryActorId: { $type: 'string' } } } { unique: true, partialFilterExpression: { foundryActorId: { $type: 'string' } } }
); );
// A player holds at most one character of a campaign: the id is unique within it.
ActorSchema.index(
{ campaign: 1, discordUserId: 1 },
{ unique: true, partialFilterExpression: { discordUserId: { $type: 'string' } } }
);
module.exports = mongoose.model('Actor', ActorSchema); module.exports = mongoose.model('Actor', ActorSchema);

View File

@@ -13,6 +13,15 @@ async function userOwnsCampaign(campaignId, userId) {
return Boolean(campaign); return Boolean(campaign);
} }
// Hit points and hit dice travel as a bar the sheet fills (`current` of `max`, see models/Actor.js).
// A partial update keeps whatever half of the pair it did not send, and `current` never passes the
// maximum it ends up with.
function barPool(existing, value) {
const max = Math.max(0, Number(value?.max ?? existing?.max) || 0);
const current = Math.max(0, Math.min(Number(value?.current ?? existing?.current) || 0, max));
return { current, max };
}
// Folders the campaign's actors are grouped into, in the shape the sidebar groups by // Folders the campaign's actors are grouped into, in the shape the sidebar groups by
// (the notes, items and maps each keep a tree of their own, see models/Folder.js). // (the notes, items and maps each keep a tree of their own, see models/Folder.js).
async function actorFolders(campaignId) { async function actorFolders(campaignId) {
@@ -56,7 +65,7 @@ router.post('/create', async (req, res) => {
router.post('/update', async (req, res) => { router.post('/update', async (req, res) => {
try { try {
const { id, name, species, className, subclass, level, abilityScores, armorClass, speed, proficiencies, inventory, traits, spells, image, folder } = req.body; const { id, name, species, className, subclass, level, abilityScores, armorClass, speed, hitPoints, hitDice, proficiencies, inventory, traits, spells, image, folder } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' }); if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const actor = await Actor.findById(id); const actor = await Actor.findById(id);
@@ -80,6 +89,8 @@ router.post('/update', async (req, res) => {
if (abilityScores !== undefined) actor.abilityScores = abilityScores; if (abilityScores !== undefined) actor.abilityScores = abilityScores;
if (armorClass !== undefined) actor.armorClass = Number(armorClass); if (armorClass !== undefined) actor.armorClass = Number(armorClass);
if (speed !== undefined) actor.speed = Number(speed); if (speed !== undefined) actor.speed = Number(speed);
if (hitPoints !== undefined) actor.hitPoints = barPool(actor.hitPoints, hitPoints);
if (hitDice !== undefined) actor.hitDice = barPool(actor.hitDice, hitDice);
if (proficiencies !== undefined) actor.proficiencies = proficiencies; if (proficiencies !== undefined) actor.proficiencies = proficiencies;
if (inventory !== undefined) actor.inventory = inventory; if (inventory !== undefined) actor.inventory = inventory;
if (traits !== undefined) actor.traits = traits; if (traits !== undefined) actor.traits = traits;

View File

@@ -16,6 +16,11 @@ function validGuildId(value) {
return /^\d{5,25}$/.test(String(value ?? '')); return /^\d{5,25}$/.test(String(value ?? ''));
} }
// Discord ids are snowflakes the same shape as guild ids.
function validUserId(value) {
return /^\d{5,25}$/.test(String(value ?? ''));
}
// Connecting a Discord server is the service link of issue: the bot asks // Connecting a Discord server is the service link of issue: the bot asks
// /api/link/start for a sign-up link, and whoever opens it signs in and picks the // /api/link/start for a sign-up link, and whoever opens it signs in and picks the
// campaign this server may read. What is left here is what the bot needs once // campaign this server may read. What is left here is what the bot needs once
@@ -179,4 +184,92 @@ router.get('/bot/guild/:guildId/actors', requireBot, async (req, res) => {
} }
}); });
// Who may take a character already held by somebody else is decided in Discord,
// where the server administrators are: the bot authenticates with the shared
// secret and says whether the person asking is one (`admin`). Everything else
// the backend still guards itself: only the guild's own campaign is reachable.
// One command per player link (Syndria98/dragonroll#72): assigning takes the
// character for `discordUserId`, and a player never holds two of them, so a
// second assign moves the player instead of doubling them up.
router.post('/bot/guild/:guildId/actors/assign', requireBot, async (req, res) => {
try {
const guildId = String(req.params.guildId);
const discordUserId = String(req.body.discordUserId ?? '');
if (!validGuildId(guildId) || !validUserId(discordUserId) || !req.body.actorId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const link = await DiscordGuildLink.findOne({ guildId }).lean();
if (!link) return res.json({ status: 'error', msg: 'discord.errors.not-connected' });
const campaign = await Campaign.findOne({ discordGuildId: guildId, createdBy: link.dragonrollUser }).select('_id name').lean();
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
const actor = await Actor.findOne({ _id: req.body.actorId, campaign: campaign._id });
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
const holder = String(actor.discordUserId ?? '');
if (holder && holder !== discordUserId && !req.body.admin) {
return res.json({ status: 'error', msg: 'discord.errors.actor-held' });
}
// The character this player hands over to take the new one.
const previous = await Actor.findOne({ campaign: campaign._id, discordUserId, _id: { $ne: actor._id } }).lean();
if (previous) {
await Actor.updateMany(
{ campaign: campaign._id, discordUserId, _id: { $ne: actor._id } },
{ $set: { discordUserId: null } }
);
}
actor.discordUserId = discordUserId;
await actor.save();
res.json({
status: 'ok',
actor: { id: String(actor._id), name: actor.name, discordUserId },
previous: previous ? { id: String(previous._id), name: previous.name } : null
});
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Freeing a character: without `actorId` the player gives up their own, with
// one a server administrator frees anybody's.
router.post('/bot/guild/:guildId/actors/unassign', requireBot, async (req, res) => {
try {
const guildId = String(req.params.guildId);
const discordUserId = String(req.body.discordUserId ?? '');
if (!validGuildId(guildId) || !validUserId(discordUserId)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const link = await DiscordGuildLink.findOne({ guildId }).lean();
if (!link) return res.json({ status: 'error', msg: 'discord.errors.not-connected' });
const campaign = await Campaign.findOne({ discordGuildId: guildId, createdBy: link.dragonrollUser }).select('_id name').lean();
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
const filter = { campaign: campaign._id };
if (req.body.actorId) filter._id = req.body.actorId;
else filter.discordUserId = discordUserId;
const actor = await Actor.findOne(filter);
if (!actor || !actor.discordUserId) return res.json({ status: 'error', msg: 'errors.notfound' });
const holder = String(actor.discordUserId);
if (holder !== discordUserId && !req.body.admin) {
return res.json({ status: 'error', msg: 'discord.errors.actor-held' });
}
actor.discordUserId = null;
await actor.save();
res.json({ status: 'ok', actor: { id: String(actor._id), name: actor.name }, wasYours: holder === discordUserId });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
module.exports = router; module.exports = router;

View File

@@ -62,24 +62,23 @@ async function saveFoundryActor(campaign, source, fullSync = false) {
: new Actor({ campaign: campaign._id }); : new Actor({ campaign: campaign._id });
} }
actor.foundryActorId = foundryActorId; actor.foundryActorId = foundryActorId;
// `created` says whether this row is new: whoever imports a whole world counts
// the rows it made apart from the ones it only wrote over.
const created = actor.isNew;
// A full snapshot runs when a GM reconnects. Preserve existing Dragonroll // A full snapshot runs when a GM reconnects. Preserve existing Dragonroll
// edits then; live Foundry change events continue to overwrite normally. // edits then; live Foundry change events continue to overwrite normally.
if (!fullSync || actor.isNew) Object.assign(actor, fields); if (!fullSync || actor.isNew) Object.assign(actor, fields);
await actor.save(); await actor.save();
return { foundryActorId, actorId: actor.id }; return { foundryActorId, actorId: actor.id, created };
} }
// A snapshot carries world-level items plus the items embedded in every actor it // The campaign's item list mirrors the world's item directory and nothing else
// sends. World items are listed first so they own a name before its copies. // (Syndria98/dragonroll#67). The items embedded in an actor are that character's own
// inventory: they travel with the actor document (see services/actor-foundry.js), so a
// snapshot feeds Item rows from the world directory (`body.items`) alone and gear a
// character merely carries stays on its sheet instead of standing in the item list.
function snapshotItemSources(body) { function snapshotItemSources(body) {
const sources = []; return Array.isArray(body.items) ? body.items : [];
if (Array.isArray(body.items)) sources.push(...body.items);
if (Array.isArray(body.actors)) {
for (const actor of body.actors) {
if (Array.isArray(actor?.items)) sources.push(...actor.items);
}
}
return sources;
} }
async function saveFoundryItem(campaign, source, fullSync = false, folders = null) { async function saveFoundryItem(campaign, source, fullSync = false, folders = null) {
@@ -95,9 +94,9 @@ async function saveFoundryItem(campaign, source, fullSync = false, folders = nul
if (flagged && (!flagged.foundryItemId || flagged.foundryItemId === foundryItemId)) item = flagged; if (flagged && (!flagged.foundryItemId || flagged.foundryItemId === foundryItemId)) item = flagged;
} }
if (!item) { if (!item) {
// The same gear exists more than once in Foundry: once in the world // A world item can share its name with a Dragonroll row the campaign made by
// directory and once inside each actor carrying it. Keep a single // hand, or with one it renamed away from. Keep a single item per name so a
// Dragonroll item per name so inventories do not flood the Item list. // piece of gear the world sends folds into that row instead of doubling it.
const sameName = await Item.find({ const sameName = await Item.find({
campaign: campaign._id, campaign: campaign._id,
$or: [{ name: fields.name }, { foundryNames: fields.name }] $or: [{ name: fields.name }, { foundryNames: fields.name }]
@@ -109,6 +108,9 @@ async function saveFoundryItem(campaign, source, fullSync = false, folders = nul
} }
item.foundryItemId = foundryItemId; item.foundryItemId = foundryItemId;
// `created` says whether this row is new: whoever imports a whole world counts
// the rows it made apart from the ones it only wrote over.
const created = item.isNew;
if (!fullSync || item.isNew) Object.assign(item, fields); if (!fullSync || item.isNew) Object.assign(item, fields);
// Foundry's own icon is kept on every save, not only when the edits above // Foundry's own icon is kept on every save, not only when the edits above
// land: the item window offers it back after the user picked their own. // land: the item window offers it back after the user picked their own.
@@ -117,14 +119,14 @@ async function saveFoundryItem(campaign, source, fullSync = false, folders = nul
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES); item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
} }
// Which folder of the campaign's item tree the world says this item stands in. // Which folder of the campaign's item tree the world says this item stands in.
// `undefined` means the push says nothing about folders — an item embedded in an // `undefined` means the push says nothing about folders — an older module that
// actor, or a module that knows nothing about them — and the item stays where it // knows nothing about them — and the item stays where it is. The world owns the
// is. The world owns the folder of its own directory, so a move it reports lands on // folder of its own directory, so a move it reports lands on a full snapshot too
// a full snapshot too and wins over one a campaign made from its item list. // and wins over one a campaign made from its item list.
const folder = resolveFoundryItemFolder(source, folders); const folder = resolveFoundryItemFolder(source, folders);
if (folder !== undefined) item.folder = folder; if (folder !== undefined) item.folder = folder;
await item.save(); await item.save();
return { foundryItemId, itemId: item.id }; return { foundryItemId, itemId: item.id, created };
} }
async function syncFoundryItems(campaign, sources, fullSync = false, folders = null) { async function syncFoundryItems(campaign, sources, fullSync = false, folders = null) {
@@ -140,9 +142,9 @@ async function syncFoundryItems(campaign, sources, fullSync = false, folders = n
// A Foundry world groups its item directory into folders; the campaign mirrors that // A Foundry world groups its item directory into folders; the campaign mirrors that
// tree as Folders of target 'item' so its item list reads like the world's. Every // tree as Folders of target 'item' so its item list reads like the world's. Every
// push from a module that knows about folders carries the whole world tree, and // push from a module that knows about folders carries the whole world tree, and
// names the folder each world item it sends stands in. Items embedded in an actor // names the folder each world item it sends stands in. Only the world's item
// say nothing: the folders they carry belong to that actor's own inventory, and // directory reaches the campaign's item list, so only its folders are mirrored; the
// Dragonroll keeps one item per piece of gear anyway. // inventory folders an actor keeps for itself are none of the item list's business.
// The colour a pushed folder carries. `undefined` means the push says nothing about // 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 // colours — an older module, which knows nothing about them — and the colour the
@@ -297,8 +299,8 @@ router.post('/sync/snapshot', async (req, res) => {
foundryActorId: { $exists: true, $nin: currentIds } foundryActorId: { $exists: true, $nin: currentIds }
}); });
} }
// Pruning needs a full snapshot: only that request sees the world // Pruning needs a full snapshot: only that request sees the whole world
// directory and every actor's copies at the same time. // directory, so it alone knows which synced rows the world has let go of.
if (fullSync && itemSources) { if (fullSync && itemSources) {
const currentIds = snapshotItemSources(req.body) const currentIds = snapshotItemSources(req.body)
.map((source) => String(source?._id || source?.id || '').trim()) .map((source) => String(source?._id || source?.id || '').trim())
@@ -451,3 +453,9 @@ router.post('/sync/map-item', async (req, res) => {
}); });
module.exports = router; module.exports = router;
// The writers every Foundry document goes through: the sync pushes above, and the
// force import a campaign asks for from its sidebar (routes/foundry.js). One set of
// rules decides which campaign row a world document owns, so pulling a world over
// twice updates its rows instead of doubling them.
module.exports.saveFoundryActor = saveFoundryActor;
module.exports.saveFoundryItem = saveFoundryItem;

View File

@@ -1,6 +1,21 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const { requestFoundry } = require('../services/foundry'); const { requestFoundry } = require('../services/foundry');
const { normalizeIconDirectory, readIconListingPage, shapeIconListing } = require('../services/foundry-icons');
const Campaign = require('../models/Campaign');
// The writers a Foundry document is stored through, shared with the sync pushes the
// linked module sends (routes/foundry-link.js) so both write a world's rows by the
// same rules.
const { saveFoundryActor, saveFoundryItem } = require('./foundry-link');
// 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. The linked world's
// id travels along: an import has to know whose data it is pulling over.
async function findOwnedCampaign(campaignId, userId) {
if (!campaignId) return null;
return Campaign.findOne({ _id: campaignId, createdBy: userId }).select('settings foundryWorldId').lean();
}
async function proxy(path, res) { async function proxy(path, res) {
try { try {
@@ -24,4 +39,95 @@ 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('/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)); router.get('/items/:id', (req, res) => proxy(`api/items/${encodeURIComponent(req.params.id)}`, res));
// Force import (Syndria98/dragonroll#77): the sidebar's "force import from Foundry"
// pulls the whole actor list or item directory of the world the bridge is showing
// right now. The documents go through the writers the module's own snapshot push
// uses, so a world document lands on the row it owns: what the campaign already has
// is written over, not imported a second time. Nothing is pruned here — only a full
// snapshot from the module sees the whole world, so dropping rows the world let go of
// stays that snapshot's job.
router.post('/import', async (req, res) => {
try {
const kind = ['actors', 'items'].includes(req.body?.kind) ? req.body.kind : null;
if (!kind) return res.json({ status: 'error', msg: 'errors.missing-data' });
const campaign = await findOwnedCampaign(req.body.campaign, req.user.id);
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!campaign.foundryWorldId) {
return res.json({ status: 'error', msg: 'foundry.errors.import-not-linked' });
}
// The bridge answers `{status, data, world}`: `data` holds the world's actors
// or its world-level items, in the shape the module published them in.
let snapshot;
try {
snapshot = await requestFoundry(`api/${kind}`);
} catch (err) {
if (err.code !== 'FOUNDRY_NOT_CONFIGURED') console.error(err);
return res.json({ status: 'error', msg: 'foundry.errors.import-unavailable' });
}
if (snapshot.status !== 200 || snapshot.data?.status !== 'ok' || !Array.isArray(snapshot.data.data)) {
return res.json({ status: 'error', msg: 'foundry.errors.import-unavailable' });
}
// The bridge keeps one world's snapshot at a time, so a campaign linked to
// another world must not be filled with it. A bridge that does not say whose
// world it holds is taken at its word: only a known mismatch stops the import.
if (snapshot.data.world?.id && snapshot.data.world.id !== campaign.foundryWorldId) {
return res.json({ status: 'error', msg: 'foundry.errors.import-world-mismatch' });
}
let imported = 0;
let updated = 0;
for (const source of snapshot.data.data) {
// An actor without a name, or a world document that is not gear, maps to
// nothing and is skipped exactly like a sync push skips it.
const mapping = kind === 'actors'
? await saveFoundryActor(campaign, source)
: await saveFoundryItem(campaign, source);
if (!mapping) continue;
if (mapping.created) imported += 1;
else updated += 1;
}
res.json({ status: 'ok', kind, imported, updated });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// 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; module.exports = router;

View 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
};

View File

@@ -1,5 +1,11 @@
async function requestFoundry(path) { async function requestFoundry(path) {
const baseUrl = process.env.FOUNDRY_API_URL; // The bridge a campaign's icon and world reads go to is the very one that
// world already pushes its snapshot to. It is often configured under
// FOUNDRY_API_CLIENT_URL alone — the address the Foundry client reaches —
// while FOUNDRY_API_URL is the optional private one the backend prefers.
// Falling back to it keeps a connected, syncing world's reads working
// instead of reporting its bridge as unset (Syndria98/dragonroll#74).
const baseUrl = process.env.FOUNDRY_API_URL || process.env.FOUNDRY_API_CLIENT_URL;
const token = process.env.FOUNDRY_API_TOKEN; const token = process.env.FOUNDRY_API_TOKEN;
if (!baseUrl || !token) { if (!baseUrl || !token) {

View File

@@ -13,12 +13,14 @@ Discord server B ──link──▶ Dragonroll campaign "Silang" (account g
## Commands ## Commands
- `/characters [type]` lists the linked campaign's actors, optionally filtered to characters, NPCs, or creatures. - `/characters [type]` lists the linked campaign's actors, optionally filtered to characters, NPCs, or creatures. Each one that a player has claimed with `/dragonroll assign` shows that player next to it.
- `/character name public:true` shows the matching actor's portrait (when one has been uploaded), profile, ability scores, combat stats, proficiencies, traits, spells, and inventory. Type part of a name to pick it from the campaign's current roster. Set `public` to `true` to show the reply to everyone in the channel. - `/character name public:true` shows the matching actor's portrait (when one has been uploaded), profile, ability scores, combat stats, proficiencies, traits, spells, and inventory. Type part of a name to pick it from the campaign's current roster. Set `public` to `true` to show the reply to everyone in the channel.
- `/dragonroll connect` starts a short-lived Dragonroll sign-in and authorization link, and confirms here once somebody authorizes the server. - `/dragonroll connect` starts a short-lived Dragonroll sign-in and authorization link, and confirms here once somebody authorizes the server.
- `/dragonroll link` lets a server administrator choose a campaign owned by the connected Dragonroll account. Type part of a campaign name to filter the choices. - `/dragonroll link` lets a server administrator choose a campaign owned by the connected Dragonroll account. Type part of a campaign name to filter the choices.
- `/dragonroll unlink` removes this server’s campaign link. - `/dragonroll unlink` removes this server’s campaign link.
- `/dragonroll status` shows the campaign linked to this server. - `/dragonroll status` shows the campaign linked to this server, and the character linked to your Discord account on it.
- `/dragonroll assign character` links that character of the campaign to your Discord account: each player holds one character, so claiming a second one frees the first. Anyone can take a free character; only a server administrator can take a character another player already holds.
- `/dragonroll unassign [character]` removes a character link. Without the option you give up your own character; naming somebody else’s character takes it off them, which only a server administrator can do.
- `/dragonroll refresh` rechecks the current connection and campaign in Dragonroll. - `/dragonroll refresh` rechecks the current connection and campaign in Dragonroll.
Replies are private by default. `/character` can be made public with its `public` option, so everyone in the channel can see the character sheet. Replies are private by default. `/character` can be made public with its `public` option, so everyone in the channel can see the character sheet.

View File

@@ -51,7 +51,24 @@ const commands = [
.setDescription('Show the campaign linked to this server.')) .setDescription('Show the campaign linked to this server.'))
.addSubcommand((subcommand) => subcommand .addSubcommand((subcommand) => subcommand
.setName('refresh') .setName('refresh')
.setDescription('Refresh this server’s Dragonroll connection status.'))) .setDescription('Refresh this server’s Dragonroll connection status.'))
.addSubcommand((subcommand) => subcommand
.setName('assign')
.setDescription('Link one character of the campaign to your Discord account.')
.addStringOption((option) => option
.setName('character')
.setDescription('Character to play (pick it from the campaign roster).')
.setRequired(true)
.setMaxLength(100)
.setAutocomplete(true)))
.addSubcommand((subcommand) => subcommand
.setName('unassign')
.setDescription('Remove the link between a character and a Discord player.')
.addStringOption((option) => option
.setName('character')
.setDescription('Character to free (yours by default, anyone’s as a server administrator).')
.setMaxLength(100)
.setAutocomplete(true))))
]; ];
module.exports = commands; module.exports = commands;

View File

@@ -123,7 +123,32 @@ function createDragonrollApi(config) {
return { campaign, actors: payload.actors }; return { campaign, actors: payload.actors };
} }
return { startAuthorization, claimLinkNotifications, getStatus, getCampaign, listCampaigns, linkCampaign, unlinkCampaign, listActors }; // Linking players to characters (Syndria98/dragonroll#72). `admin` says
// whether the Discord side already checked the person is a server
// administrator, who may move a character somebody else holds.
async function assignActor(guildId, { actorId, discordUserId, admin = false }) {
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/actors/assign`, {
method: 'POST',
body: JSON.stringify({ actorId, discordUserId: String(discordUserId), admin })
});
if (!payload.actor) throw new Error('Dragonroll returned an invalid character link.');
return { actor: payload.actor, previous: payload.previous ?? null };
}
async function unassignActor(guildId, { actorId, discordUserId, admin = false }) {
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/actors/unassign`, {
method: 'POST',
body: JSON.stringify({
discordUserId: String(discordUserId),
...(actorId ? { actorId } : {}),
admin
})
});
if (!payload.actor) throw new Error('Dragonroll returned an invalid character link.');
return { actor: payload.actor, wasYours: payload.wasYours === true };
}
return { startAuthorization, claimLinkNotifications, getStatus, getCampaign, listCampaigns, linkCampaign, unlinkCampaign, listActors, assignActor, unassignActor };
} }
module.exports = { createDragonrollApi, CampaignNotLinkedError, DragonrollNotConnectedError }; module.exports = { createDragonrollApi, CampaignNotLinkedError, DragonrollNotConnectedError };

View File

@@ -234,6 +234,20 @@ async function main() {
: 'Not linked yet.' } : 'Not linked yet.' }
); );
// The campaign's character linked to this Discord account (#72), when there is one.
if (status.campaign) {
try {
const { actors } = await dragonroll.listActors(guildId);
const yours = actors.find((actor) => String(actor.discordUserId ?? '') === interaction.user.id);
embed.addFields({
name: 'Your character',
value: yours ? safeField(yours.name, 100) : 'None. Run /dragonroll assign to link one to your Discord account.'
});
} catch {
// The roster is a bonus of this card, which stays useful without it.
}
}
if (!status.connected) { if (!status.connected) {
embed.setDescription('A server administrator can run /dragonroll connect to connect a Dragonroll account.'); embed.setDescription('A server administrator can run /dragonroll connect to connect a Dragonroll account.');
} else if (!status.campaign) { } else if (!status.campaign) {
@@ -243,6 +257,78 @@ async function main() {
await respond(interaction, { embeds: [embed] }); await respond(interaction, { embeds: [embed] });
} }
// /dragonroll assign and unassign (Syndria98/dragonroll#72): each player of the
// server holds one character of the linked campaign. Anyone claims a free
// character for themselves; server administrators also move and free the ones
// somebody else holds.
async function handleActorAssignment(interaction, guildId, subcommand) {
const isAdmin = interaction.memberPermissions?.has(PermissionFlagsBits.Administrator) === true;
const name = interaction.options.getString('character');
const { actors } = await dragonroll.listActors(guildId);
// Unassign without a character gives up the one linked to you.
if (subcommand === 'unassign' && !name) {
const mine = actors.find((actor) => String(actor.discordUserId ?? '') === interaction.user.id);
if (!mine) {
await respond(interaction, { content: 'You do not have a character linked to your Discord account here. Run `/dragonroll assign` to claim one.' });
return;
}
await dragonroll.unassignActor(guildId, { discordUserId: interaction.user.id });
await respond(interaction, { content: `You are no longer linked to **${safeField(mine.name, 100)}**.` });
return;
}
const result = findActor(actors, name);
if (!result.actor) {
await respond(interaction, {
content: result.matches?.length
? safeField(`Several characters match **${name}**: ${result.matches.slice(0, 15).map((actor) => actor.name).join(', ')}. Try a more specific name.`, 1800)
: safeField(`I couldn't find a character named **${name}**. Try \`/characters\` to see the campaign roster.`, 1800)
});
return;
}
const actor = result.actor;
const holder = String(actor.discordUserId ?? '');
if (subcommand === 'assign') {
if (holder === interaction.user.id) {
await respond(interaction, { content: `You are already linked to **${safeField(actor.name, 100)}**.` });
return;
}
if (holder && !isAdmin) {
await respond(interaction, { content: `**${safeField(actor.name, 100)}** is already linked to <@${holder}>. A server administrator can give it away and take it with the same command.` });
return;
}
const { previous } = await dragonroll.assignActor(guildId, {
actorId: String(actor._id),
discordUserId: interaction.user.id,
admin: isAdmin
});
const lines = [`You are now linked to **${safeField(actor.name, 100)}**.`];
if (holder) lines.push(`That character was linked to <@${holder}>; the link is removed.`);
if (previous) lines.push(`Your previous character, **${safeField(previous.name, 100)}**, is free again.`);
await respond(interaction, { content: safeField(lines.join('\n'), 1800) });
return;
}
// Unassign with a character named: your own, or anybody's as an administrator.
if (!holder) {
await respond(interaction, { content: `**${safeField(actor.name, 100)}** does not have a linked Discord player.` });
return;
}
if (holder !== interaction.user.id && !isAdmin) {
await respond(interaction, { content: `**${safeField(actor.name, 100)}** is linked to <@${holder}>. Only a server administrator can unlink it.` });
return;
}
await dragonroll.unassignActor(guildId, { actorId: String(actor._id), discordUserId: interaction.user.id, admin: isAdmin });
await respond(interaction, {
content: holder === interaction.user.id
? `You are no longer linked to **${safeField(actor.name, 100)}**.`
: `**${safeField(actor.name, 100)}** is no longer linked to <@${holder}>.`
});
}
client.once(Events.ClientReady, (readyClient) => { client.once(Events.ClientReady, (readyClient) => {
console.log(`Dragonroll character bot is online as ${readyClient.user.tag}, in ${readyClient.guilds.cache.size} servers.`); console.log(`Dragonroll character bot is online as ${readyClient.user.tag}, in ${readyClient.guilds.cache.size} servers.`);
// Guild commands registered when the bot joined shadow global ones and // Guild commands registered when the bot joined shadow global ones and
@@ -331,10 +417,17 @@ async function main() {
await respondActorChoices(interaction, guildId); await respondActorChoices(interaction, guildId);
return; return;
} }
if (interaction.commandName === 'dragonroll' && interaction.options.getSubcommand() === 'link') { if (interaction.commandName === 'dragonroll') {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'link') {
await respondCampaignChoices(interaction, guildId); await respondCampaignChoices(interaction, guildId);
return; return;
} }
if (['assign', 'unassign'].includes(subcommand)) {
await respondActorChoices(interaction, guildId);
return;
}
}
return; return;
} }
@@ -412,6 +505,34 @@ async function main() {
return; return;
} }
// Players link themselves to a character of the campaign (Syndria98/dragonroll#72).
if (['assign', 'unassign'].includes(subcommand)) {
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
await handleActorAssignment(interaction, guildId, subcommand);
} catch (error) {
if (error instanceof DragonrollNotConnectedError) {
await explainNotConnected(interaction, guildId);
return;
}
if (error instanceof CampaignNotLinkedError) {
await explainMissingCampaign(interaction, guildId);
return;
}
if (error.code === 'discord.errors.actor-held') {
await respond(interaction, { content: 'That character is already linked to another player. A server administrator can give it away and take it with the same command.' });
return;
}
if (error.status === 401 || error.message.includes('DRAGONROLL_DISCORD_BOT_SECRET')) {
await respond(interaction, { content: 'The bot API secret is missing or does not match the backend. Contact the bot operator.' });
return;
}
console.error(`Could not ${subcommand} a character link in Discord server ${guildId}:`, error.message);
await respond(interaction, { content: 'I could not change that character link right now. Please try again.' });
}
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await showStatus(interaction, guildId); await showStatus(interaction, guildId);
return; return;
@@ -442,7 +563,10 @@ async function main() {
const details = [actor.species, actor.className, actor.level ? `Lv. ${actor.level}` : null] const details = [actor.species, actor.className, actor.level ? `Lv. ${actor.level}` : null]
.filter(Boolean) .filter(Boolean)
.join(' · '); .join(' · ');
return `• **${actor.name}**${details ? ` — ${details}` : ''}`; // The player a character is linked to (#72); mentions never ping
// here, the replies parse no mentions.
const player = actor.discordUserId ? ` 🎮 <@${actor.discordUserId}>` : '';
return `• **${actor.name}**${details ? ` — ${details}` : ''}${player}`;
}); });
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setTitle(`Characters of ${campaign.name}`) .setTitle(`Characters of ${campaign.name}`)

View File

@@ -82,16 +82,16 @@ The optional read-only snapshot bridge is not affected: it keeps publishing the
### Items ### Items
The campaign's Item list is synchronized with the world's gear, both ways: The campaign's Item list mirrors the world's item directory (Foundry's **items tab**) and nothing
else (Syndria98/dragonroll#67):
- The GM sends the world item directory (`game.items`) with every snapshot, and world items created, - The GM sends the world item directory (`game.items`) with every snapshot, and world items created,
changed or deleted in Foundry are pushed as they happen. Items embedded in a character travel with changed or deleted in Foundry are pushed as they happen. The items embedded in a character are that
that character's snapshot instead. character's own inventory: they travel with its snapshot and stay on its sheet, so gear a character
- Gear is deduplicated by name: the same sword in the world directory and in three characters' merely carries does not stand in the campaign's item list.
inventories becomes one Dragonroll item. Names Dragonroll renames away from are remembered on the - A world item folds into a Dragonroll row that already carries its name — one a campaign made by hand,
item (`foundryNames`), so Foundry's copies keep folding into it rather than coming back as a or one it renamed away from and remembers (`foundryNames`) — instead of doubling it. Spells, classes,
duplicate. Spells, classes, subclasses, backgrounds, feats and species are not gear and are not subclasses, backgrounds, feats and species are not gear and are not imported.
imported.
- Foundry owns the fields it sends (category from the item type, rarity, quantity, weight, weapon - Foundry owns the fields it sends (category from the item type, rarity, quantity, weight, weapon
properties, description). An item made by hand in Dragonroll is created in the world's item 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 directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry
@@ -101,10 +101,9 @@ The campaign's Item list is synchronized with the world's gear, both ways:
what the GM colours in Foundry shows on the campaign's folder, and what the campaign colours lands on 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). 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 - 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 pruned only by a full snapshot, so a live item push never deletes anything: only a full snapshot sees
Dragonroll removes its Foundry world copy on the next reconcile. Items that live only in an actor's the whole world directory and can tell which synced rows it has let go of. Deleting a synced item in
inventory are owned by that actor's snapshot: editing such an item in Dragonroll does not rewrite the Dragonroll removes its Foundry world copy on the next reconcile.
actor's copy.
The module calls these Dragonroll routes with the campaign sync token (no Dragonroll login): The module calls these Dragonroll routes with the campaign sync token (no Dragonroll login):
@@ -135,6 +134,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_ALLOWED_ORIGINS='https://vtt.example.com'
export DRAGONROLL_FOUNDRY_HOST='0.0.0.0' export DRAGONROLL_FOUNDRY_HOST='0.0.0.0'
export DRAGONROLL_FOUNDRY_PORT='8787' 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 npm start --prefix foundry/bridge
``` ```
@@ -170,6 +172,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/actors/:id/items` | Items embedded in an actor |
| `GET /api/foundry/items` | World-level items | | `GET /api/foundry/items` | World-level items |
| `GET /api/foundry/items/:id` | One world-level item | | `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 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, `Authorization: Bearer <read-token>`. Responses contain `{ status: "ok", data, world, syncedAt,
@@ -177,6 +180,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 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. 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 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 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. does not create or update Foundry documents, and it does not persist the bridge cache across restarts.

View File

@@ -1,4 +1,6 @@
const http = require("node:http"); const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const { timingSafeEqual } = require("node:crypto"); const { timingSafeEqual } = require("node:crypto");
const host = process.env.DRAGONROLL_FOUNDRY_HOST || "0.0.0.0"; const host = process.env.DRAGONROLL_FOUNDRY_HOST || "0.0.0.0";
@@ -12,6 +14,9 @@ const allowedOrigins = new Set(
.filter(Boolean), .filter(Boolean),
); );
const maxBodySize = 50 * 1024 * 1024; 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) { if (!readToken || !pushToken) {
throw new Error("Set DRAGONROLL_FOUNDRY_READ_TOKEN and DRAGONROLL_FOUNDRY_PUSH_TOKEN before starting the bridge."); 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) => { const server = http.createServer(async (request, response) => {
if (!setCorsHeaders(request, response)) { if (!setCorsHeaders(request, response)) {
sendJson(response, 403, { status: "error", msg: "foundry.origin-not-allowed" }); sendJson(response, 403, { status: "error", msg: "foundry.origin-not-allowed" });
@@ -188,6 +267,10 @@ const server = http.createServer(async (request, response) => {
return; 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); const current = currentSnapshot(response);
if (!current) return; if (!current) return;

View File

@@ -23,6 +23,7 @@ let updatingPairingStatus = false;
let linkedCampaignName = ""; let linkedCampaignName = "";
let linkProblem = ""; let linkProblem = "";
let actorSyncTimeout; let actorSyncTimeout;
let characterSyncRetryTimeout;
let characterSyncRunning = false; let characterSyncRunning = false;
let actorSyncErrorLogged = false; let actorSyncErrorLogged = false;
const syncingActorIds = new Set(); const syncingActorIds = new Set();
@@ -529,8 +530,9 @@ async function pushFoundryActors(actors, fullSync = false) {
const result = await postDragonroll("foundry/sync/snapshot", { const result = await postDragonroll("foundry/sync/snapshot", {
worldId: game.world.id, worldId: game.world.id,
actors: supportedActors.map(serializeFoundryActor), actors: supportedActors.map(serializeFoundryActor),
// Dragonroll deduplicates by name, so sending the world directory next to // The world item directory is what the campaign lists as its items
// the actor copies keeps a single Item per piece of gear. // (Syndria98/dragonroll#67); the gear a character carries travels inside that
// actor's snapshot as its inventory, not as campaign items.
items: getWorldItemSnapshots(), items: getWorldItemSnapshots(),
// The folder tree those world items stand in (see worldItemFolderSnapshots). // The folder tree those world items stand in (see worldItemFolderSnapshots).
folders: worldItemFolderSnapshots(), folders: worldItemFolderSnapshots(),
@@ -1269,6 +1271,14 @@ async function reconcileDragonrollCharacters() {
} }
} }
// Both sides converge on a timer that only runs while the world is open, so a
// round that could not reach Dragonroll is asked for again in a while instead of
// leaving the campaign with whatever it happened to receive.
function scheduleDragonrollCharacterSync(delay = 15000) {
clearTimeout(characterSyncRetryTimeout);
characterSyncRetryTimeout = setTimeout(reconcileDragonrollCharacters, delay);
}
async function initializeCharacterSync() { async function initializeCharacterSync() {
if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return; if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return;
try { try {

View File

@@ -30,9 +30,19 @@ $themes: (
container-shadow: #151d28, container-shadow: #151d28,
sticky-header-bg: #20202077, sticky-header-bg: #20202077,
red: #e06c75, // Quoted: red/green/gray are also Sass colour keywords, so unquoted they are parsed as
green: #98c379, // colour values, and interpolating one into `--color-#{$name}` warns
gray: #cccccc, // (Syndria98/dragonroll#71).
"red": #e06c75,
"green": #98c379,
"gray": #cccccc,
// The rarity of an item colours its row in the sidebar (Syndria98/dragonroll#63).
rarity-common: #ffffff,
rarity-uncommon: #1eff00,
rarity-rare: #2f81f7,
rarity-very-rare: #a855f7,
rarity-legendary: #ff8000,
icon-invert: 100%, icon-invert: 100%,
@@ -68,9 +78,17 @@ $themes: (
container-shadow: #5f6774, container-shadow: #5f6774,
sticky-header-bg: #fff, sticky-header-bg: #fff,
red: #e06c75, // Quoted for the same reason as in the dark map.
green: #98c379, "red": #e06c75,
gray: #cccccc, "green": #98c379,
"gray": #cccccc,
// Same rarities as the dark map, darkened to stay readable on a light background.
rarity-common: #1e1e1e,
rarity-uncommon: #157f2b,
rarity-rare: #1d4ed8,
rarity-very-rare: #7e22ce,
rarity-legendary: #c05621,
icon-invert: 0%, icon-invert: 0%,

View File

@@ -8,6 +8,7 @@ import { emitter } from '~/services/Emitter';
import { BuildColorMenu } from '~/services/EntryColors'; import { BuildColorMenu } from '~/services/EntryColors';
import { BuildItemRows } from '~/services/ItemFolders'; import { BuildItemRows } from '~/services/ItemFolders';
import Server, { getBaseUrl } from '~/services/Server'; import Server, { getBaseUrl } from '~/services/Server';
import { DisplayToast } from '~/services/Toaster';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows'; import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu'; import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
import { ACTOR_DRAG_TYPE } from '~/services/MapTokens'; import { ACTOR_DRAG_TYPE } from '~/services/MapTokens';
@@ -29,6 +30,9 @@ const entryFolders = { actor: ref([]), item: ref([]), map: ref([]) };
const collapsedFolderIds = ref([]); const collapsedFolderIds = ref([]);
const loadingNotes = ref(false); const loadingNotes = ref(false);
const loadingEntries = ref(false); const loadingEntries = ref(false);
// An import of the whole linked world takes a moment, and clicking the row again while
// it runs must not start a second one.
const importingFoundry = ref(false);
const notesError = ref(''); const notesError = ref('');
const entriesError = ref(''); const entriesError = ref('');
const sidebarCollapsed = ref(false); const sidebarCollapsed = ref(false);
@@ -279,8 +283,13 @@ function entrySummary(actor) {
return bits.join(' · '); return bits.join(' · ');
} }
function itemSummary(item) { // The rarity of an item colours the text of its row instead of listing category, rarity and
return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`; // quantity (Syndria98/dragonroll#63): common white, uncommon green, rare blue, very rare purple,
// legendary orange. Anything else (artifact) keeps the default text colour.
function rarityClass(item) {
return ['common', 'uncommon', 'rare', 'very-rare', 'legendary'].includes(item.rarity)
? `rarity-${item.rarity}`
: '';
} }
// An item's icon in the sidebar: an uploaded filename served from /api/public, or a full URL // An item's icon in the sidebar: an uploaded filename served from /api/public, or a full URL
@@ -304,6 +313,35 @@ function editMap(map) {
CreateWindow('create_map', { campaign: campaignId.value, entry: map }); CreateWindow('create_map', { campaign: campaignId.value, entry: map });
} }
// The one sidebar action that asks the linked world instead of the campaign's own rows
// (Syndria98/dragonroll#77): the backend reads what the Foundry bridge is showing and
// writes every actor or item of it through the writers a sync push uses, so the rows
// the campaign already has are written over and only the world's new ones are made.
// The list is read back once the answer is in, so whatever arrived is on screen, and
// the toast says how the world landed.
async function forceImportFromFoundry(entityType) {
const section = sectionForTarget(entityType);
if (!campaignId.value || !section || importingFoundry.value) return;
importingFoundry.value = true;
try {
const response = await Server().post('/foundry/import', { campaign: campaignId.value, kind: section });
if (response.data.status !== 'ok') {
DisplayToast('red', t(response.data.msg || 'campaigns.foundry-import.error'), 3000);
return;
}
DisplayToast('green', t('campaigns.foundry-import.done', {
imported: response.data.imported ?? 0,
updated: response.data.updated ?? 0
}), 3000);
await fetchCampaignEntries(section);
} catch (error) {
DisplayToast('red', t('campaigns.foundry-import.error'), 3000);
} finally {
importingFoundry.value = false;
}
}
function showEntryMenu(entry, entityType) { function showEntryMenu(entry, entityType) {
const list = entryLists[entityType]; const list = entryLists[entityType];
const menuItems = []; const menuItems = [];
@@ -323,6 +361,18 @@ function showEntryMenu(entry, entityType) {
}); });
} }
// The actor and item lists mirror a linked Foundry world, so their rows also offer
// to pull the whole world over: this row is not sent or fetched on its own, the
// section's whole list is imported and the rows already in it are only updated.
if (entityType === 'actor' || entityType === 'item') {
menuItems.push({ divider: true });
menuItems.push({
name: t('campaigns.foundry-import.run'),
icon: '/icons/iconoir/regular/import.svg',
action: () => { HideContextMenu(); forceImportFromFoundry(entityType); }
});
}
// Rows of every section can be filed into a folder of their own list, like a note // Rows of every section can be filed into a folder of their own list, like a note
// into a folder of the note tree. // into a folder of the note tree.
menuItems.push({ menuItems.push({
@@ -681,9 +731,8 @@ onBeforeUnmount(() => {
<span v-if="row.item.image" class="entity-entry-image" aria-hidden="true"> <span v-if="row.item.image" class="entity-entry-image" aria-hidden="true">
<img :src="itemImageUrl(row.item.image)" alt=""> <img :src="itemImageUrl(row.item.image)" alt="">
</span> </span>
<span class="entity-entry-name">{{ row.item.name }}</span> <span class="entity-entry-name" :class="rarityClass(row.item)">{{ row.item.name }}</span>
</span> </span>
<span class="entity-entry-meta">{{ itemSummary(row.item) }}</span>
</div> </div>
</template> </template>
</template> </template>
@@ -877,6 +926,13 @@ onBeforeUnmount(() => {
/* An item row leads with the item's own icon on the left of its name, standing in for the /* 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). */ "SYNCED" text it used to show (Syndria98/dragonroll#53). */
.entity-entry-title { display: flex; align-items: center; gap: 9px; min-width: 0; } .entity-entry-title { display: flex; align-items: center; gap: 9px; min-width: 0; }
/* The rarity of an item colours the text of its row (Syndria98/dragonroll#63): common white,
uncommon green, rare blue, very rare purple, legendary orange. */
.entity-entry-name.rarity-common { color: var(--color-rarity-common); }
.entity-entry-name.rarity-uncommon { color: var(--color-rarity-uncommon); }
.entity-entry-name.rarity-rare { color: var(--color-rarity-rare); }
.entity-entry-name.rarity-very-rare { color: var(--color-rarity-very-rare); }
.entity-entry-name.rarity-legendary { color: var(--color-rarity-legendary); }
.entity-entry-image { .entity-entry-image {
flex: 0 0 30px; width: 30px; height: 30px; box-sizing: border-box; flex: 0 0 30px; width: 30px; height: 30px; box-sizing: border-box;
display: grid; place-items: center; overflow: hidden; display: grid; place-items: center; overflow: hidden;

View File

@@ -34,6 +34,11 @@ const tabs = [
]; ];
const activeTab = ref('abilities'); const activeTab = ref('abilities');
// Les pestanyes pengen del marc de la finestra, per fora del contingent (vegeu .sheet-tabs). La
// finestra es fa més estreta perquè el marge que la centra sigui prou ample per aguantar-les;
// per sota de 760px el marc les fa estar a dins i el marge deixa de fer falta.
const TAB_RAIL_WIDTH = 150;
function normalizeActor(actor) { function normalizeActor(actor) {
return { return {
name: actor?.name ?? '', name: actor?.name ?? '',
@@ -44,6 +49,16 @@ function normalizeActor(actor) {
abilityScores: Object.fromEntries(abilityStats.map(({ key }) => [key, Number(actor?.abilityScores?.[key] ?? 10)])), abilityScores: Object.fromEntries(abilityStats.map(({ key }) => [key, Number(actor?.abilityScores?.[key] ?? 10)])),
armorClass: Number(actor?.armorClass ?? 10), armorClass: Number(actor?.armorClass ?? 10),
speed: Number(actor?.speed ?? 30), speed: Number(actor?.speed ?? 30),
// Les barres sota la imatge: `current` de `max`. Un personatge que encara no en té
// rep un dau de cop per nivell, que és el que D&D compta.
hitPoints: {
current: Number(actor?.hitPoints?.current ?? actor?.hitPoints?.max ?? 10),
max: Number(actor?.hitPoints?.max ?? actor?.hitPoints?.current ?? 10)
},
hitDice: {
current: Number(actor?.hitDice?.current ?? actor?.level ?? 1),
max: Number(actor?.hitDice?.max ?? actor?.level ?? 1)
},
proficiencies: actor?.proficiencies ?? '', proficiencies: actor?.proficiencies ?? '',
inventory: (actor?.inventory ?? []).map((item) => ({ inventory: (actor?.inventory ?? []).map((item) => ({
name: item.name ?? '', quantity: Number(item.quantity ?? 1), weight: Number(item.weight ?? 0) name: item.name ?? '', quantity: Number(item.quantity ?? 1), weight: Number(item.weight ?? 0)
@@ -60,8 +75,11 @@ original.value = normalizeActor(props.data.actor);
onMounted(() => { onMounted(() => {
Top(wrapper); Top(wrapper);
SetupHandle(id, handle); SetupHandle(id, handle);
// Les pestanyes pengen del marc per fora del cos: com que la finestra es centra, el marge que
// li queda a la dreta és la meitat del que li sobra, i cal reservar-nos el doble.
const railRoom = window.innerWidth > 760 ? 2 * TAB_RAIL_WIDTH : 0;
SetSize(id, { SetSize(id, {
width: Math.max(320, Math.min(900, window.innerWidth - 24)), width: Math.max(320, Math.min(900, window.innerWidth - 24 - railRoom)),
height: Math.max(360, Math.min(700, window.innerHeight - 32)) height: Math.max(360, Math.min(700, window.innerHeight - 32))
}); });
ResetPosition(id, 'center'); ResetPosition(id, 'center');
@@ -79,6 +97,15 @@ onMounted(() => emitter.on('campaign-entry-updated', handleActorSync));
onBeforeUnmount(() => emitter.off('campaign-entry-updated', handleActorSync)); onBeforeUnmount(() => emitter.off('campaign-entry-updated', handleActorSync));
const proficiencyBonus = computed(() => Math.ceil(form.value.level / 4) + 1); const proficiencyBonus = computed(() => Math.ceil(form.value.level / 4) + 1);
// La iniciativa és el modificador de DESTÀ, que és el que D&D compta quan el personatge no
// porta cap do extra que l'augmenti.
const initiativeBonus = computed(() => abilityModifier(form.value.abilityScores.dex));
// Quina part del màxim representa la barra; buida (màxim 0) o per sobre, tot tallat.
function barPercent(current, max) {
return max > 0 ? Math.min(100, Math.max(0, ((Number(current) || 0) / max) * 100)) : 0;
}
const hitPointsPercent = computed(() => barPercent(form.value.hitPoints.current, form.value.hitPoints.max));
const hitDicePercent = computed(() => barPercent(form.value.hitDice.current, form.value.hitDice.max));
const carryingCapacity = computed(() => form.value.abilityScores.str * 15); const carryingCapacity = computed(() => form.value.abilityScores.str * 15);
const carriedWeight = computed(() => form.value.inventory.reduce((total, item) => total + (Number(item.quantity) || 0) * (Number(item.weight) || 0), 0)); const carriedWeight = computed(() => form.value.inventory.reduce((total, item) => total + (Number(item.quantity) || 0) * (Number(item.weight) || 0), 0));
const carryPercent = computed(() => Math.min(100, carryingCapacity.value ? (carriedWeight.value / carryingCapacity.value) * 100 : 0)); const carryPercent = computed(() => Math.min(100, carryingCapacity.value ? (carriedWeight.value / carryingCapacity.value) * 100 : 0));
@@ -179,6 +206,21 @@ async function saveSheet() {
<template> <template>
<div class="window-wrapper sheet-window" :id="'window-wrapper-' + id" ref="wrapper"> <div class="window-wrapper sheet-window" :id="'window-wrapper-' + id" ref="wrapper">
<WindowHandle :window="id" ref="handle" /> <WindowHandle :window="id" ref="handle" />
<!-- Pestilletes del marc de la finestra: pengen del cantó dret, per fora del
contingent, i no s'enrolen quan la fitxa desfila. -->
<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 class="sheet-body"> <div class="sheet-body">
<header class="sheet-hero"> <header class="sheet-hero">
<div class="character-mark" aria-hidden="true">{{ form.name.slice(0, 1).toUpperCase() }}</div> <div class="character-mark" aria-hidden="true">{{ form.name.slice(0, 1).toUpperCase() }}</div>
@@ -217,9 +259,8 @@ async function saveSheet() {
<div v-if="error" class="sheet-error">{{ error }}</div> <div v-if="error" class="sheet-error">{{ error }}</div>
<div class="sheet-layout">
<div class="sheet-content">
<main v-show="activeTab === 'abilities'" class="sheet-grid"> <main v-show="activeTab === 'abilities'" class="sheet-grid">
<div class="character-column">
<div v-if="form.image || editing" class="sheet-portrait" :class="{ empty: !form.image }"> <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')"> <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"> <button v-if="editing && !form.image" class="portrait-upload" type="button" :disabled="uploadingPhoto" @click="pickPhoto">
@@ -234,6 +275,58 @@ async function saveSheet() {
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onPhotoSelected"> <input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onPhotoSelected">
</div> </div>
<!-- El que es mira primer: classe d'armadura, velocitat i els bonificadors
que acompanyen els cops, tot just sota la imatge. -->
<section class="sheet-panel vitals-panel">
<div class="vital-stats">
<div class="vital-stat">
<span>{{ $t('campaigns.character-sheet.armor-class') }}</span>
<input v-if="editing" v-model.number="form.armorClass" type="number" min="0" :aria-label="$t('campaigns.character-sheet.armor-class')">
<strong v-else>{{ form.armorClass }}</strong>
</div>
<div class="vital-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" :aria-label="$t('campaigns.character-sheet.speed')"><small>ft</small></label>
<strong v-else>{{ form.speed }} <small>ft</small></strong>
</div>
<div class="vital-stat">
<span>{{ $t('campaigns.character-sheet.proficiency-bonus') }}</span>
<strong>+{{ proficiencyBonus }}</strong>
</div>
<div class="vital-stat">
<span>{{ $t('campaigns.character-sheet.initiative') }}</span>
<strong>{{ initiativeBonus }}</strong>
</div>
</div>
<div class="vital-bar hit-points-bar">
<div class="vital-bar-head">
<span>{{ $t('campaigns.character-sheet.hit-points') }}</span>
<strong v-if="!editing">{{ form.hitPoints.current }} / {{ form.hitPoints.max }}</strong>
<label v-else class="vital-bar-inputs">
<input v-model.number="form.hitPoints.current" type="number" min="0" :aria-label="$t('campaigns.character-sheet.hit-points')">
<span>/</span>
<input v-model.number="form.hitPoints.max" type="number" min="0" :aria-label="$t('campaigns.character-sheet.max-hit-points')">
</label>
</div>
<div class="vital-bar-track"><div class="vital-bar-fill" :style="{ width: `${hitPointsPercent}%` }" /></div>
</div>
<div class="vital-bar hit-dice-bar">
<div class="vital-bar-head">
<span>{{ $t('campaigns.character-sheet.hit-dice') }}</span>
<strong v-if="!editing">{{ form.hitDice.current }} / {{ form.hitDice.max }}</strong>
<label v-else class="vital-bar-inputs">
<input v-model.number="form.hitDice.current" type="number" min="0" :aria-label="$t('campaigns.character-sheet.hit-dice')">
<span>/</span>
<input v-model.number="form.hitDice.max" type="number" min="0" :aria-label="$t('campaigns.character-sheet.max-hit-dice')">
</label>
</div>
<div class="vital-bar-track"><div class="vital-bar-fill" :style="{ width: `${hitDicePercent}%` }" /></div>
</div>
</section>
</div>
<section class="sheet-panel abilities-panel"> <section class="sheet-panel abilities-panel">
<h2>{{ $t('campaigns.character-sheet.ability-scores') }}</h2> <h2>{{ $t('campaigns.character-sheet.ability-scores') }}</h2>
<div class="ability-grid"> <div class="ability-grid">
@@ -244,28 +337,11 @@ async function saveSheet() {
<span class="ability-modifier">{{ abilityModifier(form.abilityScores[stat.key]) }}</span> <span class="ability-modifier">{{ abilityModifier(form.abilityScores[stat.key]) }}</span>
</div> </div>
</div> </div>
<div class="proficiency-badge">
<span>{{ $t('campaigns.character-sheet.proficiency-bonus') }}</span>
<strong>+{{ proficiencyBonus }}</strong>
</div>
</section> </section>
<section class="sheet-panel combat-panel"> <section class="sheet-panel proficiencies-panel">
<h2>{{ $t('campaigns.character-sheet.combat') }}</h2> <h2>{{ $t('campaigns.character-sheet.proficiencies') }}</h2>
<div class="combat-stats"> <textarea v-if="editing" v-model="form.proficiencies" rows="7" :placeholder="$t('campaigns.character-sheet.proficiencies-placeholder')" />
<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> <p v-else class="sheet-copy">{{ form.proficiencies || $t('campaigns.character-sheet.empty-proficiencies') }}</p>
</section> </section>
</main> </main>
@@ -321,21 +397,6 @@ async function saveSheet() {
</section> </section>
</main> </main>
</div> </div>
<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> </div>
</template> </template>
@@ -359,15 +420,15 @@ async function saveSheet() {
.sheet-button:disabled { opacity: .55; cursor: wait; } .sheet-button:disabled { opacity: .55; cursor: wait; }
.sheet-button.compact { padding: 5px 9px; font-size: 12px; } .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; 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-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; } /* Pestilletes del marc: arrencen del cantó dret de la finestra, per fora del cos, i queden
fora del contingent que desfila. Per sota de 760px no hi ha lloc fora (vegeu a sota). */
.sheet-tabs { position: absolute; left: 100%; top: 34px; display: flex; flex-direction: column; align-items: flex-start; gap: 5px; padding-top: 6px; }
.sheet-tab { .sheet-tab {
text-align: left; text-align: left;
padding: 9px 14px 9px 11px; padding: 9px 14px 9px 11px;
border: 1px solid var(--color-border); border: 1px solid var(--color-border);
border-left-width: 3px; border-left: 0;
border-radius: 0 9px 9px 0; border-radius: 0 9px 9px 0;
background: var(--color-background-soft); background: var(--color-background-soft);
color: var(--color-text); color: var(--color-text);
@@ -378,11 +439,11 @@ async function saveSheet() {
transition: background .15s ease, border-color .15s ease, color .15s ease; transition: background .15s ease, border-color .15s ease, color .15s ease;
} }
.sheet-tab:hover { background: var(--color-button-hover); } .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-tab.active { background: var(--color-background-light); color: var(--color-link); border-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 { 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 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; } .sheet-panel h3 { margin: 13px 0 7px; font: 14px MrEavesRemake; }
.sheet-portrait { grid-column: 1; grid-row: 1 / -1; position: relative; overflow: hidden; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-soft); } .sheet-portrait { position: relative; overflow: hidden; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-soft); }
.sheet-portrait.empty { display: grid; place-items: center; min-height: 220px; border-style: dashed; } .sheet-portrait.empty { display: grid; place-items: center; min-height: 220px; border-style: dashed; }
.sheet-portrait img { display: block; width: 100%; height: auto; } .sheet-portrait img { display: block; width: 100%; height: auto; }
.portrait-upload { border: 0; padding: 8px 10px; background: transparent; color: var(--color-link); font-size: 12px; cursor: pointer; } .portrait-upload { border: 0; padding: 8px 10px; background: transparent; color: var(--color-link); font-size: 12px; cursor: pointer; }
@@ -392,21 +453,34 @@ async function saveSheet() {
.portrait-controls button:hover { background: var(--color-button-hover); } .portrait-controls button:hover { background: var(--color-button-hover); }
.portrait-controls button:disabled { opacity: .55; cursor: wait; } .portrait-controls button:disabled { opacity: .55; cursor: wait; }
.photo-input { display: none; } .photo-input { display: none; }
/* La columna de la fitxa: la imatge dalt i, just a sota, el que es consulta d'anada i
tornada — classe d'armadura, velocitat, bonificadors i les barres de cops. */
.character-column { grid-column: 1; grid-row: 1 / -1; display: flex; flex-direction: column; gap: 11px; min-width: 0; }
.abilities-panel { grid-column: 2 / -1; grid-row: 1; } .abilities-panel { grid-column: 2 / -1; grid-row: 1; }
.combat-panel { grid-column: 2 / -1; grid-row: 2; } .proficiencies-panel { grid-column: 2 / -1; grid-row: 2; }
.ability-grid { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 7px; } .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-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; } .ability-label { font-size: 11px; font-weight: 700; letter-spacing: .08em; opacity: .75; }
.ability-score { font: 25px MrEavesRemake; } .ability-score { font: 25px MrEavesRemake; }
.ability-modifier { min-width: 33px; text-align: center; padding: 2px 5px; border-radius: 999px; background: var(--color-background); font-size: 12px; } .ability-modifier { min-width: 33px; text-align: center; padding: 2px 5px; border-radius: 999px; background: var(--color-background); font-size: 12px; }
.ability-card input { width: 55px; text-align: center; font-size: 21px; } .ability-card input { width: 55px; text-align: center; font-size: 21px; }
.proficiency-badge { display: flex; justify-content: space-between; align-items: center; margin-top: 9px; padding: 8px; border-radius: 8px; background: var(--color-background-soft); font-size: 12px; } .vitals-panel { display: flex; flex-direction: column; gap: 11px; }
.proficiency-badge strong { font-size: 15px; color: var(--color-link); } .vital-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; }
.combat-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } .vital-stat { min-height: 68px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; padding: 6px 4px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); text-align: center; }
.combat-stat { min-height: 72px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 5px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); } .vital-stat > span { font-size: 10px; text-transform: uppercase; letter-spacing: .05em; opacity: .72; }
.combat-stat > span { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; opacity: .72; } .vital-stat > strong { font: 25px MrEavesRemake; }
.combat-stat > strong { font: 25px MrEavesRemake; } .vital-stat small { font-size: 11px; opacity: .7; }
.combat-stat small { font-size: 11px; opacity: .7; } .vital-stat input { width: 57px; text-align: center; }
/* Les dues barres: punts de cop i daus de cop, plenes fins on arriben. */
.vital-bar-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
.vital-bar-head > span { font-size: 10px; text-transform: uppercase; letter-spacing: .05em; opacity: .72; }
.vital-bar-head > strong { font: 15px MrEavesRemake; white-space: nowrap; }
.vital-bar-inputs { display: flex; align-items: center; gap: 4px; }
.vital-bar-inputs input { width: 52px; text-align: center; }
.vital-bar-track { height: 8px; margin-top: 5px; overflow: hidden; border-radius: 999px; background: var(--color-background); }
.vital-bar-fill { height: 100%; border-radius: inherit; transition: width .2s ease; }
.hit-points-bar .vital-bar-fill { background: var(--color-red); }
.hit-dice-bar .vital-bar-fill { background: var(--color-link); }
.number-with-unit { display: flex; align-items: center; gap: 4px; } .number-with-unit { display: flex; align-items: center; gap: 4px; }
.number-with-unit input { width: 57px; } .number-with-unit input { width: 57px; }
.sheet-copy { min-height: 74px; margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; line-height: 1.45; opacity: .85; } .sheet-copy { min-height: 74px; margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; line-height: 1.45; opacity: .85; }
@@ -434,16 +508,16 @@ textarea { resize: vertical; width: 100%; min-height: 88px; 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; } .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) { @media (max-width: 760px) {
.sheet-grid { grid-template-columns: 1fr; grid-template-rows: none; } .sheet-grid { grid-template-columns: 1fr; grid-template-rows: none; }
.sheet-portrait, .abilities-panel, .combat-panel { grid-column: 1 / -1; grid-row: auto; } .character-column, .abilities-panel, .proficiencies-panel { grid-column: 1 / -1; grid-row: auto; }
/* El cantó dret no dona prou per penjar-hi les pestanyes: llavors es queden al marc, per
dins, en una filera sota la barra de la finestra. */
.sheet-tabs { position: static; align-self: stretch; flex-direction: row; flex-wrap: wrap; gap: 4px; padding: 6px 8px 0; }
.sheet-tab { flex: 1 1 auto; text-align: center; border-left: 1px solid var(--color-border); border-radius: 8px 8px 0 0; }
} }
@media (max-width: 520px) { @media (max-width: 520px) {
.sheet-body { padding: 10px; } .sheet-body { padding: 10px; }
.sheet-hero { align-items: flex-start; flex-wrap: wrap; } .sheet-hero { align-items: flex-start; flex-wrap: wrap; }
.sheet-actions { margin-left: auto; } .sheet-actions { margin-left: auto; }
.ability-grid { grid-template-columns: repeat(3, minmax(0, 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> </style>

View File

@@ -20,13 +20,13 @@ function initialForm() {
if (!editing) { if (!editing) {
return { return {
name: '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '', name: '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '',
category: 'adventuring-gear', rarity: 'common', quantity: 1, weight: '', properties: '', description: '' category: 'adventuring-gear', rarity: 'common', weight: '', properties: '', description: ''
}; };
} }
return { return {
name: editing.name ?? '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '', name: editing.name ?? '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '',
category: editing.category ?? 'adventuring-gear', rarity: editing.rarity ?? 'common', category: editing.category ?? 'adventuring-gear', rarity: editing.rarity ?? 'common',
quantity: editing.quantity ?? 1, weight: editing.weight ?? '', properties: editing.properties ?? '', weight: editing.weight ?? '', properties: editing.properties ?? '',
description: editing.description ?? '' description: editing.description ?? ''
}; };
} }
@@ -49,7 +49,7 @@ async function saveEntry() {
? { name: form.value.name.trim(), campaign: data.campaign } ? { name: form.value.name.trim(), campaign: data.campaign }
: { name: form.value.name.trim(), ...(editing ? { id: editing._id } : { campaign: data.campaign }) }; : { name: form.value.name.trim(), ...(editing ? { id: editing._id } : { campaign: data.campaign }) };
if (!isActor) { if (!isActor) {
for (const field of ['category', 'rarity', 'quantity', 'weight', 'properties', 'description']) { for (const field of ['category', 'rarity', 'weight', 'properties', 'description']) {
payload[field] = form.value[field]; payload[field] = form.value[field];
} }
} }
@@ -105,10 +105,6 @@ async function saveEntry() {
<option value="artifact">{{ $t('campaigns.item.rarities.artifact') }}</option> <option value="artifact">{{ $t('campaigns.item.rarities.artifact') }}</option>
</select> </select>
</label> </label>
<label class="form-field">
<span>{{ $t('campaigns.item.quantity') }}</span>
<input v-model.number="form.quantity" type="number" min="1" required>
</label>
<label class="form-field"> <label class="form-field">
<span>{{ $t('campaigns.item.weight') }}</span> <span>{{ $t('campaigns.item.weight') }}</span>
<input v-model="form.weight" type="number" min="0" step="0.1"> <input v-model="form.weight" type="number" min="0" step="0.1">

View File

@@ -0,0 +1,171 @@
<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) {
// The route answers every real failure with an i18n key in `msg`, but
// axios rejects a non-2xx response, so this catch would otherwise blame
// the bridge for anything at all — a campaign without a world address,
// a folder that went missing. Read the reason off the response and say
// that instead (Syndria98/dragonroll#74).
error.value = t(requestError.response?.data?.msg || '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>

View 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>

View File

@@ -1,9 +1,10 @@
<script setup> <script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'; import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n'; 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 WindowHandle from './partials/WindowHandle.vue';
import Server, { getBaseUrl } from '~/services/Server'; import Server, { getBaseUrl } from '~/services/Server';
import { useCampaignService } from '~/services/Campaign.js';
import { emitter } from '~/services/Emitter'; import { emitter } from '~/services/Emitter';
const props = defineProps(['data']); const props = defineProps(['data']);
@@ -12,9 +13,10 @@ const itemId = props.data.item?._id;
const handle = ref(null); const handle = ref(null);
const wrapper = ref(null); const wrapper = ref(null);
const error = ref(''); const error = ref('');
const uploadingIcon = ref(false); // Set while this window writes the item's icon, so a Foundry sync landing behind
const applyingFoundryIcon = ref(false); // the window does not rewrite the form under the change being made.
const photoInput = ref(null); const applyingIcon = ref(false);
const { Campaign } = useCampaignService();
const { t } = useI18n(); const { t } = useI18n();
function normalizeItem(item) { function normalizeItem(item) {
@@ -22,7 +24,6 @@ function normalizeItem(item) {
name: item?.name ?? '', name: item?.name ?? '',
category: item?.category ?? 'adventuring-gear', category: item?.category ?? 'adventuring-gear',
rarity: item?.rarity ?? 'common', rarity: item?.rarity ?? 'common',
quantity: Number(item?.quantity ?? 1),
weight: item?.weight ?? '', weight: item?.weight ?? '',
properties: item?.properties ?? '', properties: item?.properties ?? '',
description: item?.description ?? '', description: item?.description ?? '',
@@ -44,9 +45,10 @@ onMounted(() => {
onBeforeUnmount(() => ClearWindow({ type: 'item_sheet' })); onBeforeUnmount(() => ClearWindow({ type: 'item_sheet' }));
// The sidebar keeps this entry fresh (Foundry sync lands in the background); // 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 }) { 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); form.value = normalizeItem(entry);
} }
@@ -70,40 +72,22 @@ async function updateItem(payload) {
return true; return true;
} }
function pickIcon() { // Choosing an icon is a window of its own: upload one from this device, or browse
photoInput.value?.click(); // the icon library of the linked Foundry world. Both leave their result on the
} // `campaign-entry-updated` event, which this window follows.
function chooseIcon() {
async function onIconSelected(event) { CreateChildWindow(id, 'item_icon_source', {
const file = event.target.files?.[0]; item: { _id: itemId, name: form.value.name, image: form.value.image },
event.target.value = ''; campaign: Campaign.value?._id || ''
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 // The world's own icon for this item: the module keeps it on the item, so this
// item, so this just switches back to it. // just switches back to it. Picking one of the world's other icons is what the
// icon browser is for.
async function useFoundryIcon() { async function useFoundryIcon() {
if (!canUseFoundryIcon.value || applyingFoundryIcon.value) return; if (!canUseFoundryIcon.value || applyingIcon.value) return;
applyingFoundryIcon.value = true; applyingIcon.value = true;
error.value = ''; error.value = '';
try { try {
const done = await updateItem({ image: form.value.foundryImage }); const done = await updateItem({ image: form.value.foundryImage });
@@ -111,18 +95,21 @@ async function useFoundryIcon() {
} catch (requestError) { } catch (requestError) {
error.value = t('campaigns.item.sheet.save-error'); error.value = t('campaigns.item.sheet.save-error');
} finally { } finally {
applyingFoundryIcon.value = false; applyingIcon.value = false;
} }
} }
async function removeIcon() { async function removeIcon() {
if (!form.value.image) return; if (!form.value.image || applyingIcon.value) return;
applyingIcon.value = true;
error.value = ''; error.value = '';
try { try {
const done = await updateItem({ image: '' }); const done = await updateItem({ image: '' });
if (!done) error.value = t('campaigns.item.sheet.save-error'); if (!done) error.value = t('campaigns.item.sheet.save-error');
} catch (requestError) { } catch (requestError) {
error.value = t('campaigns.item.sheet.save-error'); error.value = t('campaigns.item.sheet.save-error');
} finally {
applyingIcon.value = false;
} }
} }
</script> </script>
@@ -132,10 +119,12 @@ async function removeIcon() {
<WindowHandle :window="id" ref="handle" /> <WindowHandle :window="id" ref="handle" />
<div class="item-body"> <div class="item-body">
<header class="item-hero"> <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')"> <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> <span v-else aria-hidden="true">{{ form.name.slice(0, 1).toUpperCase() }}</span>
</div> </button>
<div class="item-identity"> <div class="item-identity">
<h1>{{ form.name }}</h1> <h1>{{ form.name }}</h1>
<div class="item-tags"> <div class="item-tags">
@@ -149,23 +138,18 @@ async function removeIcon() {
<div v-if="error" class="item-error">{{ error }}</div> <div v-if="error" class="item-error">{{ error }}</div>
<div class="icon-controls"> <div class="icon-controls">
<button class="sheet-button" type="button" :disabled="uploadingIcon" @click="pickIcon"> <button class="sheet-button" type="button" @click="chooseIcon">
{{ uploadingIcon {{ form.image ? $t('campaigns.item.sheet.change-icon') : $t('campaigns.item.sheet.choose-icon') }}
? $t('campaigns.item.sheet.uploading')
: (form.image ? $t('campaigns.item.sheet.change-icon') : $t('campaigns.item.sheet.choose-icon')) }}
</button> </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') }} {{ $t('campaigns.item.sheet.foundry-icon') }}
</button> </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> <button v-if="form.image" class="sheet-button secondary" type="button" :disabled="applyingIcon" :aria-label="$t('campaigns.item.sheet.remove-icon')" @click="removeIcon">×</button>
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onIconSelected">
</div> </div>
<!-- Quantity is the actor inventory's business (Syndria98/dragonroll#63); the item
sheet only states what the item itself is. -->
<dl class="item-facts"> <dl class="item-facts">
<div class="item-fact">
<dt>{{ $t('campaigns.item.quantity') }}</dt>
<dd>{{ form.quantity }}</dd>
</div>
<div v-if="form.weight !== '' && form.weight !== undefined" class="item-fact"> <div v-if="form.weight !== '' && form.weight !== undefined" class="item-fact">
<dt>{{ $t('campaigns.item.weight') }}</dt> <dt>{{ $t('campaigns.item.weight') }}</dt>
<dd>{{ Number(form.weight).toFixed(1) }} lb</dd> <dd>{{ Number(form.weight).toFixed(1) }} lb</dd>
@@ -189,7 +173,8 @@ async function removeIcon() {
.item-window { min-width: 0; min-height: 0; } .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-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-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.empty { border-style: dashed; }
.item-icon img { width: 100%; height: 100%; object-fit: contain; } .item-icon img { width: 100%; height: 100%; object-fit: contain; }
.item-identity { min-width: 0; } .item-identity { min-width: 0; }
@@ -202,7 +187,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 { 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:hover { background: var(--color-button-hover); }
.sheet-button:disabled { opacity: .55; cursor: wait; } .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-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 { 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; } .item-fact dt { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; opacity: .72; }

View File

@@ -88,6 +88,21 @@ const defWindows = {
close: () => ClearWindow({type: 'item_sheet'}), close: () => ClearWindow({type: 'item_sheet'}),
movable: true 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: { create_map: {
title: 'windows.create-map', title: 'windows.create-map',
component: () => import('~/components/windows/CreateMapWindow.vue'), component: () => import('~/components/windows/CreateMapWindow.vue'),

View File

@@ -49,6 +49,11 @@
"rename": "Canvia el nom", "color": "Color", "default": "Per defecte", "delete": "Suprimeix la carpeta", "rename": "Canvia el nom", "color": "Color", "default": "Per defecte", "delete": "Suprimeix la carpeta",
"move-to": "Mou a carpeta...", "root": "Arrel" "move-to": "Mou a carpeta...", "root": "Arrel"
}, },
"foundry-import": {
"run": "Força la importació des del Foundry",
"done": "Importat del Foundry: {imported} nous, {updated} actualitzats.",
"error": "No s'ha pogut importar des del món del Foundry vinculat."
},
"states": { "states": {
"loading": "Carregant...", "loading-notes": "Carregant notes...", "empty-notes": "Encara no hi ha notes en aquesta campanya.", "loading": "Carregant...", "loading-notes": "Carregant notes...", "empty-notes": "Encara no hi ha notes en aquesta campanya.",
"empty-actors": "Encara no hi ha actors ni personatges.", "empty-items": "Encara no hi ha objectes en aquesta campanya.", "empty-actors": "Encara no hi ha actors ni personatges.", "empty-items": "Encara no hi ha objectes en aquesta campanya.",
@@ -65,14 +70,19 @@
}, },
"item": { "item": {
"new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.", "new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.",
"category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat", "category": "Categoria", "rarity": "Raresa",
"quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
"sheet": { "sheet": {
"icon": "Icona de l'objecte", "choose-icon": "Tria la teva pròpia icona", "change-icon": "Canvia la icona", "icon": "Icona de l'objecte", "choose-icon": "Tria la teva pròpia icona", "change-icon": "Canvia la icona",
"uploading": "Pujant...", "upload-error": "No s'ha pogut pujar aquesta icona.", "uploading": "Pujant...", "upload-error": "No s'ha pogut pujar aquesta icona.",
"foundry-icon": "Fes servir la icona del Foundry", "remove-icon": "Treu la icona", "save-error": "No s'ha pogut desar aquest objecte.", "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." "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": { "categories": {
"weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura", "weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura",
"magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre" "magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre"
@@ -108,7 +118,8 @@
"tabs": { "abilities": "Característiques", "inventory": "Inventari", "traits": "Trets", "spells": "Conjurs" }, "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", "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", "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", "combat": "Combat", "armor-class": "Classe d'armadura", "speed": "Velocitat", "initiative": "Iniciativa",
"hit-points": "Punts de cop", "max-hit-points": "Punts de cop màxims", "hit-dice": "Daus de cop", "max-hit-dice": "Daus de cop màxims", "proficiencies": "Competències",
"proficiencies-placeholder": "Afegeix salvacions, habilitats, armadures, armes, eines i idiomes...", "empty-proficiencies": "No hi ha competències afegides.", "proficiencies-placeholder": "Afegeix salvacions, habilitats, armadures, armes, eines i idiomes...", "empty-proficiencies": "No hi ha competències afegides.",
"traits": "Trets", "traits-placeholder": "Afegeix trets, capacitats i altres detalls...", "empty-traits": "No hi ha trets afegits.", "traits": "Trets", "traits-placeholder": "Afegeix trets, capacitats i altres detalls...", "empty-traits": "No hi ha trets afegits.",
"spells": "Conjurs", "spells-placeholder": "Escriu els conjurs, un per línia...", "empty-spells": "No hi ha conjurs afegits.", "spells": "Conjurs", "spells-placeholder": "Escriu els conjurs, un per línia...", "empty-spells": "No hi ha conjurs afegits.",

View File

@@ -3,6 +3,18 @@
"link-expired": "El codi d'enllaç de Foundry no és vàlid, ha caducat o ja s'ha utilitzat.", "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.", "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.", "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.",
"import-not-linked": "Aquesta campanya no té cap món del Foundry vinculat. Connecteu-ne un als ajustos de la campanya, a la pestanya d'integracions.",
"import-unavailable": "Les dades del Foundry no són disponibles: el seu bridge no està configurat, ara mateix no hi arriba o el seu món encara no ha publicat res.",
"import-world-mismatch": "El bridge del Foundry està mostrant un món diferent del que aquesta campanya té vinculat."
},
"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"
} }
} }

View File

@@ -10,5 +10,7 @@
"create-map": "Crear mapa", "create-map": "Crear mapa",
"map-viewer": "Mapa", "map-viewer": "Mapa",
"pinned-note": "Nota fixada", "pinned-note": "Nota fixada",
"item-sheet": "Objecte" "item-sheet": "Objecte",
"icon-source": "Tria una icona",
"foundry-icons": "Icones del Foundry"
} }

View File

@@ -53,6 +53,11 @@
"rename": "Rename", "color": "Color", "default": "Default", "delete": "Delete folder", "rename": "Rename", "color": "Color", "default": "Default", "delete": "Delete folder",
"move-to": "Move to folder...", "root": "Root" "move-to": "Move to folder...", "root": "Root"
}, },
"foundry-import": {
"run": "Force import from Foundry",
"done": "Imported from Foundry: {imported} new, {updated} updated.",
"error": "Unable to import from the linked Foundry world."
},
"states": { "states": {
"loading": "Loading...", "loading-notes": "Loading notes...", "empty-notes": "No notes in this campaign yet.", "loading": "Loading...", "loading-notes": "Loading notes...", "empty-notes": "No notes in this campaign yet.",
"empty-actors": "No actors or characters yet.", "empty-items": "No items in this campaign yet.", "empty-actors": "No actors or characters yet.", "empty-items": "No items in this campaign yet.",
@@ -69,14 +74,19 @@
}, },
"item": { "item": {
"new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.", "new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.",
"category": "Category", "rarity": "Rarity", "quantity": "Quantity", "category": "Category", "rarity": "Rarity",
"quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
"sheet": { "sheet": {
"icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change icon", "icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change icon",
"uploading": "Uploading...", "upload-error": "Unable to upload this icon.", "uploading": "Uploading...", "upload-error": "Unable to upload this icon.",
"foundry-icon": "Use Foundry icon", "remove-icon": "Remove icon", "save-error": "Unable to save this item.", "foundry-icon": "Use Foundry icon", "remove-icon": "Remove icon", "save-error": "Unable to save this item.",
"no-description": "No description added." "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": { "categories": {
"weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear", "weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear",
"magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other" "magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other"
@@ -114,7 +124,8 @@
"saving": "Saving...", "save": "Save sheet", "save-error": "Unable to save this character sheet.", "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", "photo": "Photo", "upload-photo": "Upload photo", "change-photo": "Change photo", "remove-photo": "Remove photo",
"uploading-photo": "Uploading...", "photo-error": "Unable to upload this photo.", "ability-scores": "Ability Scores", "proficiency-bonus": "Proficiency Bonus", "uploading-photo": "Uploading...", "photo-error": "Unable to upload this photo.", "ability-scores": "Ability Scores", "proficiency-bonus": "Proficiency Bonus",
"combat": "Combat", "armor-class": "Armor Class", "speed": "Speed", "proficiencies": "Proficiencies", "combat": "Combat", "armor-class": "Armor Class", "speed": "Speed", "initiative": "Initiative",
"hit-points": "Hit Points", "max-hit-points": "Maximum hit points", "hit-dice": "Hit Dice", "max-hit-dice": "Maximum hit dice", "proficiencies": "Proficiencies",
"proficiencies-placeholder": "Add saving throws, skills, armor, weapons, tools, and languages...", "empty-proficiencies": "No proficiencies added.", "proficiencies-placeholder": "Add saving throws, skills, armor, weapons, tools, and languages...", "empty-proficiencies": "No proficiencies added.",
"traits": "Traits", "traits-placeholder": "Add features, traits, and other character details...", "empty-traits": "No traits added.", "traits": "Traits", "traits-placeholder": "Add features, traits, and other character details...", "empty-traits": "No traits added.",
"spells": "Spells", "spells-placeholder": "List spells, one per line...", "empty-spells": "No spells added.", "spells": "Spells", "spells-placeholder": "List spells, one per line...", "empty-spells": "No spells added.",

View File

@@ -3,6 +3,18 @@
"link-expired": "This Foundry pairing code is invalid, expired, or already used.", "link-expired": "This Foundry pairing code is invalid, expired, or already used.",
"world-already-linked": "This Foundry world is already linked to another campaign.", "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.", "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.",
"import-not-linked": "This campaign has no Foundry world linked to it. Connect one under campaign settings, in the Integrations tab.",
"import-unavailable": "Foundry's data is not available: its bridge is not set up, it cannot be reached right now, or its world has not published anything yet.",
"import-world-mismatch": "The Foundry bridge is showing another world than the one this campaign is linked to."
},
"icons": {
"path": "Icon folder",
"up": "One folder up",
"loading": "Loading icons...",
"empty": "No icons to pick in this folder.",
"load-more": "Load more icons"
} }
} }

View File

@@ -10,5 +10,7 @@
"create-map": "Create Map", "create-map": "Create Map",
"map-viewer": "Map", "map-viewer": "Map",
"pinned-note": "Pinned note", "pinned-note": "Pinned note",
"item-sheet": "Item" "item-sheet": "Item",
"icon-source": "Choose an icon",
"foundry-icons": "Foundry icons"
} }

View File

@@ -49,6 +49,11 @@
"rename": "Renombrar", "color": "Color", "default": "Por defecto", "delete": "Eliminar carpeta", "rename": "Renombrar", "color": "Color", "default": "Por defecto", "delete": "Eliminar carpeta",
"move-to": "Mover a carpeta...", "root": "Raíz" "move-to": "Mover a carpeta...", "root": "Raíz"
}, },
"foundry-import": {
"run": "Forzar importación desde Foundry",
"done": "Importado desde Foundry: {imported} nuevos, {updated} actualizados.",
"error": "No se ha podido importar desde el mundo de Foundry vinculado."
},
"states": { "states": {
"loading": "Cargando...", "loading-notes": "Cargando notas...", "empty-notes": "Aún no hay notas en esta campaña.", "loading": "Cargando...", "loading-notes": "Cargando notas...", "empty-notes": "Aún no hay notas en esta campaña.",
"empty-actors": "Aún no hay actores ni personajes.", "empty-items": "Aún no hay objetos en esta campaña.", "empty-actors": "Aún no hay actores ni personajes.", "empty-items": "Aún no hay objetos en esta campaña.",
@@ -65,14 +70,19 @@
}, },
"item": { "item": {
"new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.", "new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.",
"category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad", "category": "Categoría", "rarity": "Rareza",
"quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
"sheet": { "sheet": {
"icon": "Icono del objeto", "choose-icon": "Elegir tu propio icono", "change-icon": "Cambiar icono", "icon": "Icono del objeto", "choose-icon": "Elegir tu propio icono", "change-icon": "Cambiar icono",
"uploading": "Subiendo...", "upload-error": "No se pudo subir este icono.", "uploading": "Subiendo...", "upload-error": "No se pudo subir este icono.",
"foundry-icon": "Usar el icono de Foundry", "remove-icon": "Quitar el icono", "save-error": "No se pudo guardar este objeto.", "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." "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": { "categories": {
"weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura", "weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura",
"magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro" "magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro"
@@ -108,7 +118,8 @@
"tabs": { "abilities": "Características", "inventory": "Inventario", "traits": "Rasgos", "spells": "Conjuros" }, "tabs": { "abilities": "Características", "inventory": "Inventario", "traits": "Rasgos", "spells": "Conjuros" },
"level": "Nivel", "species": "Especie", "unset-species": "Especie sin definir", "edit": "Editar hoja", "cancel": "Cancelar", "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", "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", "combat": "Combate", "armor-class": "Clase de armadura", "speed": "Velocidad", "initiative": "Iniciativa",
"hit-points": "Puntos de golpe", "max-hit-points": "Puntos de golpe máximos", "hit-dice": "Dados de golpe", "max-hit-dice": "Dados de golpe máximos", "proficiencies": "Competencias",
"proficiencies-placeholder": "Añade salvaciones, habilidades, armaduras, armas, herramientas e idiomas...", "empty-proficiencies": "No hay competencias añadidas.", "proficiencies-placeholder": "Añade salvaciones, habilidades, armaduras, armas, herramientas e idiomas...", "empty-proficiencies": "No hay competencias añadidas.",
"traits": "Rasgos", "traits-placeholder": "Añade rasgos, capacidades y otros detalles...", "empty-traits": "No hay rasgos añadidos.", "traits": "Rasgos", "traits-placeholder": "Añade rasgos, capacidades y otros detalles...", "empty-traits": "No hay rasgos añadidos.",
"spells": "Conjuros", "spells-placeholder": "Escribe los conjuros, uno por línea...", "empty-spells": "No hay conjuros añadidos.", "spells": "Conjuros", "spells-placeholder": "Escribe los conjuros, uno por línea...", "empty-spells": "No hay conjuros añadidos.",

View File

@@ -3,6 +3,18 @@
"link-expired": "El código de vinculación de Foundry no es válido, ha caducado o ya se ha usado.", "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.", "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.", "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.",
"import-not-linked": "Esta campaña no tiene ningún mundo de Foundry vinculado. Conecte uno en los ajustes de la campaña, en la pestaña de integraciones.",
"import-unavailable": "Los datos de Foundry no están disponibles: su bridge no está configurado, no es accesible ahora o su mundo todavía no ha publicado nada.",
"import-world-mismatch": "El bridge de Foundry está mostrando un mundo distinto del que esta campaña tiene vinculado."
},
"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"
} }
} }

View File

@@ -10,5 +10,7 @@
"create-map": "Crear mapa", "create-map": "Crear mapa",
"map-viewer": "Mapa", "map-viewer": "Mapa",
"pinned-note": "Nota fijada", "pinned-note": "Nota fijada",
"item-sheet": "Objeto" "item-sheet": "Objeto",
"icon-source": "Elegir icono",
"foundry-icons": "Iconos de Foundry"
} }

View File

@@ -0,0 +1,167 @@
// Tests for Syndria98/dragonroll#64, the second round of modifications to the character sheet:
// * the tab rail hangs off the border of the window instead of standing inside the sheet body,
// * the armor class, the speed, the proficiency bonus and the initiative bonus stand under the
// portrait, together with the hit points and the hit dice, both drawn as bars.
//
// The window is a `.vue` file and the repository root installs no dependencies for it, so its
// template and styles are read out of the source the way tests/character-sheet-tabs.test.js reads
// them. The plain functions the sheet and the route work out their numbers with are lifted out of
// those sources and called, the way tests/map-viewer.test.js runs a service it cannot import.
//
// 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] ?? "";
const actorModelSource = read("backend", "src", "models", "Actor.js");
const actorRouteSource = read("backend", "src", "routes", "actor.js");
// `fromSource` hands back one top-level declaration as a value. Imports and refs are module scope
// the test does not have, so the few names a declaration reads are passed in as arguments. The
// declaration runs in this realm, so the objects it builds compare with the ones the test builds.
function fromSource(source, pattern, locals = {}) {
const declaration = pattern.exec(source)?.[0];
assert.ok(declaration, `expected ${pattern} in the source`);
const name = /(?:const|function)\s+(\w+)/.exec(declaration)[1];
return new Function(...Object.keys(locals), `${declaration}\n;return ${name};`)(...Object.values(locals));
}
const abilityStats = fromSource(script, /const abilityStats = \[[\s\S]*?\];/);
const normalizeActor = fromSource(script, /function normalizeActor\(actor\) \{[\s\S]*?\n\}/, { abilityStats });
const barPercent = fromSource(script, /function barPercent\(current, max\) \{[\s\S]*?\n\}/);
const barPool = fromSource(actorRouteSource, /function barPool\(existing, value\) \{[\s\S]*?\n\}/);
// The column that opens the abilities tab: the portrait with everything under it.
function portraitColumn() {
const start = template.indexOf('<div class="character-column">');
const end = template.indexOf('<section class="sheet-panel abilities-panel">');
assert.ok(start !== -1 && end > start, "expected a character column ahead of the ability scores");
return template.slice(start, end);
}
test("the tab rail hangs off the border of the window, outside the sheet body", () => {
const rail = /\.sheet-tabs\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
assert.match(rail, /position:\s*absolute/, "the rail is mounted on the window frame");
assert.match(rail, /left:\s*100%/, "it starts at the right border and reaches outwards");
assert.ok(
template.indexOf('<nav class="sheet-tabs"') < template.indexOf('<div class="sheet-body">'),
"the rail is a child of the window, ahead of the body it hangs beside"
);
const body = /\.sheet-body\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
assert.match(body, /overflow:\s*auto/, "the sheet body scrolls on its own, the rail stays put");
});
test("the armor class, the speed and both bonuses stand under the portrait", () => {
const column = portraitColumn();
assert.ok(column.includes('class="sheet-portrait"'), "the portrait opens the column");
assert.ok(column.includes('class="sheet-panel vitals-panel"'), "the readouts follow the image");
assert.ok(
column.indexOf('class="sheet-portrait"') < column.indexOf("vitals-panel"),
"the readouts stand under the image, not above it"
);
for (const key of ["armor-class", "speed", "proficiency-bonus", "initiative"]) {
assert.ok(
column.includes(`campaigns.character-sheet.${key}`),
`the ${key} belongs under the image`
);
}
// Gone from where they were: the combat panel is nothing but proficiencies left over, and the
// ability scores panel keeps the six scores only.
assert.doesNotMatch(template, /combat-panel/, "the combat panel went with the combat stats");
const abilities = template
.slice(template.indexOf('<section class="sheet-panel abilities-panel">'))
.split("</section>")[0];
assert.doesNotMatch(abilities, /proficiency-bonus/, "the proficiency bonus moved down the column");
assert.match(abilities, /campaigns\.character-sheet\.ability-scores/);
});
test("the hit points and the hit dice stand as bars under the portrait", () => {
const column = portraitColumn();
assert.match(column, /class="vital-bar hit-points-bar"/);
assert.match(column, /class="vital-bar hit-dice-bar"/);
for (const pool of ["hitPoints", "hitDice"]) {
assert.match(column, new RegExp(`v-model\\.number="form\\.${pool}\\.current"`), `${pool} is editable`);
assert.match(column, new RegExp(`v-model\\.number="form\\.${pool}\\.max"`), `${pool} has a maximum to set`);
assert.match(
column,
new RegExp(`\\{\\{ form\\.${pool}\\.current \\}\\} / \\{\\{ form\\.${pool}\\.max \\}\\}`),
`${pool} reads current of max outside of editing`
);
}
// Each bar fills what its own maximum allows, and each is painted its own colour.
assert.match(column, /:style="\{ width: `\$\{hitPointsPercent\}%` \}"/);
assert.match(column, /:style="\{ width: `\$\{hitDicePercent\}%` \}"/);
assert.match(sheetSource, /\.hit-points-bar \.vital-bar-fill\s*\{[^}]*var\(--color-red\)/);
assert.match(sheetSource, /\.hit-dice-bar \.vital-bar-fill\s*\{[^}]*var\(--color-link\)/);
});
test("a bar fills what its maximum allows, no more and no less", () => {
assert.equal(barPercent(5, 10), 50);
assert.equal(barPercent(12, 10), 100, "healed past the maximum does not overflow the track");
assert.equal(barPercent(-3, 10), 0, "nothing left stands empty");
assert.equal(barPercent(4, 0), 0, "a maximum of nothing is no bar either");
assert.equal(barPercent("", 10), 0, "an input cleared mid-edit is read as nothing");
});
test("the initiative bonus is the modifier of dexterity", () => {
assert.match(
script,
/const initiativeBonus = computed\(\(\) => abilityModifier\(form\.value\.abilityScores\.dex\)\)/,
"D&D counts initiative as the dexterity modifier while the character carries no extra bonus"
);
const abilityModifier = fromSource(script, /function abilityModifier\(score\) \{[\s\S]*?\n\}/);
assert.equal(abilityModifier(16), "+3");
assert.equal(abilityModifier(10), "+0", "the sheet writes a flat modifier with its sign, as the ability cards do");
assert.equal(abilityModifier(9), "-1");
});
test("an actor carries its pools, and one without them starts on its level", () => {
assert.deepEqual(normalizeActor({ level: 3 }).hitPoints, { current: 10, max: 10 });
assert.deepEqual(normalizeActor({ level: 3 }).hitDice, { current: 3, max: 3 }, "one die per level");
const wounded = normalizeActor({
level: 5,
hitPoints: { current: 4, max: 44 },
hitDice: { current: 2, max: 5 }
});
assert.deepEqual(wounded.hitPoints, { current: 4, max: 44 });
assert.deepEqual(wounded.hitDice, { current: 2, max: 5 });
});
test("the Actor model stores both pools as current of a maximum", () => {
for (const pool of ["hitPoints", "hitDice"]) {
assert.match(
actorModelSource,
new RegExp(`${pool}:\\s*\\{\\s*current:\\s*\\{\\s*type:\\s*Number[^}]*\\},\\s*max:\\s*\\{\\s*type:\\s*Number[^}]*\\}`),
`${pool} holds a current and a maximum`
);
}
});
test("the actor update takes both pools and never lets one pass its maximum", () => {
assert.match(actorRouteSource, /const \{[^}]*hitPoints[^}]*hitDice[^}]*\} = req\.body;/, "the update reads them off the body");
assert.match(actorRouteSource, /if \(hitPoints !== undefined\) actor\.hitPoints = barPool\(actor\.hitPoints, hitPoints\)/);
assert.match(actorRouteSource, /if \(hitDice !== undefined\) actor\.hitDice = barPool\(actor\.hitDice, hitDice\)/);
assert.deepEqual(barPool({ current: 5, max: 20 }, { current: 8, max: 30 }), { current: 8, max: 30 });
assert.deepEqual(barPool({ current: 5, max: 20 }, { current: 40 }), { current: 20, max: 20 }, "a current over its maximum stops at the maximum");
assert.deepEqual(barPool({ current: 5, max: 20 }, { max: 4 }), { current: 4, max: 4 }, "a maximum lowered below the current pulls it down");
assert.deepEqual(barPool({ current: 5, max: 20 }, { current: 12 }), { current: 12, max: 20 }, "half a pair keeps the half it did not send");
assert.deepEqual(barPool({ current: 5, max: 20 }, { current: -2, max: 20 }), { current: 0, max: 20 });
});
test("every locale names the readouts that moved under the portrait", () => {
for (const locale of ["en", "es", "ca"]) {
const sheet = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"))["character-sheet"];
for (const key of ["initiative", "hit-points", "max-hit-points", "hit-dice", "max-hit-dice"]) {
assert.ok(sheet[key], `${locale} is missing campaigns.character-sheet.${key}`);
}
}
});

View File

@@ -37,9 +37,10 @@ test("the tabs sit on the right as a vertical bookmark rail", () => {
assert.match(template, /v-for="tab in tabs"[\s\S]*?:aria-selected="activeTab === tab\.key"/); assert.match(template, /v-for="tab in tabs"[\s\S]*?:aria-selected="activeTab === tab\.key"/);
const rail = /\.sheet-tabs\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? ""; const rail = /\.sheet-tabs\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
assert.match(rail, /flex-direction:\s*column/, "the bookmarks stack down the right edge"); 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 // #64 moved the rail out of the content: it hangs off the window border itself, so it is not
assert.match(sheetSource, /\.sheet-layout\s*\{[^}]*display:\s*flex[^}]*\}/, "content and rail share a row"); // swept along when the sheet scrolls (see tests/character-sheet-portrait-column.test.js).
assert.match(sheetSource, /\.sheet-content\s*\{[^}]*flex:\s*1[^}]*\}/, "the content takes the room, the rail stays slim"); assert.match(rail, /position:\s*absolute/, "the rail is mounted on the window frame");
assert.match(rail, /left:\s*100%/, "the rail stands outside the window's right border");
}); });
// Each tab shows only its own panels; the rest are hidden with v-show so an in-progress edit is // Each tab shows only its own panels; the rest are hidden with v-show so an in-progress edit is
@@ -54,7 +55,7 @@ test("every tab shows only its own content and hides the others", () => {
const abilities = tabBody("abilities"); const abilities = tabBody("abilities");
assert.match(abilities, /class="sheet-portrait"/, "the portrait stays with ability scores"); 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 abilities-panel"/);
assert.match(abilities, /class="sheet-panel combat-panel"/, "combat rides with the ability scores"); assert.match(abilities, /class="sheet-panel proficiencies-panel"/, "the proficiencies ride with the ability scores");
for (const other of ["inventory-panel", "traits-panel", "spells-panel"]) { for (const other of ["inventory-panel", "traits-panel", "spells-panel"]) {
assert.doesNotMatch(abilities, new RegExp(other)); assert.doesNotMatch(abilities, new RegExp(other));
} }

View File

@@ -0,0 +1,290 @@
// Tests for linking the characters of a campaign to the Discord players of the server it is
// linked to (Syndria98/dragonroll#72): each player holds one character, anybody claims a free
// one for themselves, and only a server administrator moves or frees one somebody else holds.
//
// Same set-up as tests/map-tokens.test.js, which the repository root runs without installing
// anything: the express router of routes/discord.js is loaded into `node:vm` with its models
// stubbed, and the last checks read the sources of the bot, whose command wiring is what has
// to stay right.
//
// 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 vm = require("node:vm");
function readRepoFile(...parts) {
return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
}
// A mongoose query answers whatever `await query` and `query.lean()` answer with, and lets `select()`
// and `sort()` sit in between.
function mongooseQuery(value) {
const result = {
select: () => result,
sort: () => result,
lean: () => Promise.resolve(value),
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
};
return result;
}
const GUILD_ID = "12345678901234567";
const PLAYER = "1111111111111111111";
const OTHER_PLAYER = "2222222222222222222";
// The pieces of a filter the routes build against actors: the campaign, the player holding the
// character, and plain or `$ne` ids.
function actorMatches(actor, filter = {}) {
if (filter.campaign !== undefined && String(actor.campaign) !== String(filter.campaign)) return false;
if (filter.discordUserId !== undefined && String(actor.discordUserId ?? null) !== String(filter.discordUserId ?? null)) return false;
if (filter._id !== undefined) {
if (filter._id && typeof filter._id === "object" && filter._id.$ne !== undefined) {
if (String(actor._id) === String(filter._id.$ne)) return false;
} else if (String(actor._id) !== String(filter._id)) return false;
}
return true;
}
// Loads routes/discord.js over a store of actors, a guild link and the campaign that guild holds.
function loadDiscordRoutes({ guildLink = { guildId: GUILD_ID, dragonrollUser: "user-1" }, campaign = { _id: "campaign-1", name: "Katlum" }, actors = [] } = {}) {
const store = actors.map((actor) => ({ campaign: "campaign-1", discordUserId: null, save: async () => {}, ...actor }));
const routes = new Map();
const router = {
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
delete: () => {},
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id === "../models/Actor") return {
findOne: (filter) => {
const actor = store.find((candidate) => actorMatches(candidate, filter));
return mongooseQuery(actor ?? null);
},
find: (filter) => mongooseQuery(store.filter((candidate) => actorMatches(candidate, filter))
.slice()
.sort((a, b) => String(a.name).localeCompare(String(b.name)))),
updateMany: async (filter, update) => {
let modifiedCount = 0;
for (const actor of store) {
if (!actorMatches(actor, filter)) continue;
if (update.$set && "discordUserId" in update.$set) actor.discordUserId = update.$set.discordUserId;
modifiedCount += 1;
}
return { modifiedCount };
},
};
if (id === "../models/Campaign") return { findOne: () => mongooseQuery(campaign) };
if (id === "../models/DiscordGuildLink") return { findOne: () => mongooseQuery(guildLink) };
if (id === "../models/ServiceLinkRequest") return {};
if (id === "../models/User") return {};
if (id === "../services/service-links") return { requireDiscordBot: (req, res, next) => next(), NOTIFICATION_WINDOW_MS: 1 };
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(readRepoFile("backend", "src", "routes", "discord.js"), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
async function call(route, { body = {}, params = {} } = {}) {
const handlers = routes.get(route);
assert.ok(handlers, `${route} is not mounted`);
const res = { payload: null, json(payload) { this.payload = payload; } };
// The last handler of the chain, skipping the bot-secret gate the harness stands behind.
await handlers[handlers.length - 1]({ body, params: { guildId: GUILD_ID, ...params } }, res);
return res.payload;
}
function actor(id) {
return store.find((candidate) => candidate._id === id);
}
return { call, actor };
}
const ASSIGN = "POST /bot/guild/:guildId/actors/assign";
const UNASSIGN = "POST /bot/guild/:guildId/actors/unassign";
function assignmentRouteTests() {
test("assigning links one campaign character to a Discord player", async () => {
const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum" }] });
const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } });
assert.equal(response.status, "ok");
assert.deepEqual(response.actor, { id: "actor-1", name: "Katlum", discordUserId: PLAYER });
assert.equal(api.actor("actor-1").discordUserId, PLAYER);
assert.equal(response.previous, null);
});
test("a player never holds two characters: taking a second one frees the first", async () => {
const api = loadDiscordRoutes({
actors: [
{ _id: "actor-1", name: "Katlum", discordUserId: PLAYER },
{ _id: "actor-2", name: "Solus" }
]
});
const response = await api.call(ASSIGN, { body: { actorId: "actor-2", discordUserId: PLAYER } });
assert.equal(response.status, "ok");
assert.equal(api.actor("actor-1").discordUserId, null);
assert.equal(api.actor("actor-2").discordUserId, PLAYER);
assert.deepEqual(response.previous, { id: "actor-1", name: "Katlum" });
});
test("a player cannot take a character another player already holds", async () => {
const api = loadDiscordRoutes({
actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }]
});
const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } });
assert.equal(response.msg, "discord.errors.actor-held");
assert.equal(api.actor("actor-1").discordUserId, OTHER_PLAYER);
});
test("a server administrator moves a held character to themselves", async () => {
const api = loadDiscordRoutes({
actors: [
{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER },
{ _id: "actor-2", name: "Solus", discordUserId: PLAYER }
]
});
const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER, admin: true } });
assert.equal(response.status, "ok");
assert.equal(api.actor("actor-1").discordUserId, PLAYER);
assert.equal(api.actor("actor-2").discordUserId, null);
});
test("unassigning without a character frees the one linked to the player", async () => {
const api = loadDiscordRoutes({
actors: [
{ _id: "actor-1", name: "Katlum", discordUserId: PLAYER },
{ _id: "actor-2", name: "Silang", discordUserId: OTHER_PLAYER }
]
});
const response = await api.call(UNASSIGN, { body: { discordUserId: PLAYER } });
assert.equal(response.status, "ok");
assert.deepEqual(response.actor, { id: "actor-1", name: "Katlum" });
assert.equal(response.wasYours, true);
assert.equal(api.actor("actor-1").discordUserId, null);
assert.equal(api.actor("actor-2").discordUserId, OTHER_PLAYER);
});
test("a player cannot unassign a character held by somebody else", async () => {
const api = loadDiscordRoutes({
actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }]
});
const response = await api.call(UNASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } });
assert.equal(response.msg, "discord.errors.actor-held");
assert.equal(api.actor("actor-1").discordUserId, OTHER_PLAYER);
});
test("a server administrator frees anybody's character", async () => {
const api = loadDiscordRoutes({
actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }]
});
const response = await api.call(UNASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER, admin: true } });
assert.equal(response.status, "ok");
assert.equal(response.wasYours, false);
assert.equal(api.actor("actor-1").discordUserId, null);
});
}
function assignmentGuardTests() {
test("linking needs a guild with a connected account and a linked campaign", async () => {
const connected = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum" }] });
assert.equal((await connected.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).status, "ok");
const notLinked = loadDiscordRoutes({ guildLink: null });
assert.equal((await notLinked.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).msg, "discord.errors.not-connected");
assert.equal((await notLinked.call(UNASSIGN, { body: { discordUserId: PLAYER } })).msg, "discord.errors.not-connected");
const noCampaign = loadDiscordRoutes({ campaign: null });
assert.equal((await noCampaign.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).msg, "errors.notfound");
});
test("linking needs a whole player and one of the campaign's own characters", async () => {
const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum", campaign: "campaign-1" }] });
assert.equal((await api.call(ASSIGN, { body: { discordUserId: PLAYER } })).msg, "errors.missing-data");
assert.equal((await api.call(ASSIGN, { body: { actorId: "actor-1" } })).msg, "errors.missing-data");
assert.equal((await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: "bob" } })).msg, "errors.missing-data");
assert.equal((await api.call(UNASSIGN, { body: {} })).msg, "errors.missing-data");
const otherCampaign = loadDiscordRoutes({ actors: [{ _id: "actor-9", name: "Stranger", campaign: "campaign-2" }] });
assert.equal((await otherCampaign.call(ASSIGN, { body: { actorId: "actor-9", discordUserId: PLAYER } })).msg, "errors.notfound");
});
test("the bot roster carries the player linked to each character", async () => {
const api = loadDiscordRoutes({
actors: [
{ _id: "actor-1", name: "Katlum", discordUserId: PLAYER },
{ _id: "actor-2", name: "Solus" }
]
});
const response = await api.call("GET /bot/guild/:guildId/actors");
assert.equal(response.status, "ok");
assert.deepEqual(response.actors.map((actor) => actor.discordUserId), [PLAYER, null]);
});
}
function botWiringTests() {
const commands = readRepoFile("discord-bot", "src", "commands.js");
const api = readRepoFile("discord-bot", "src", "dragonroll-api.js");
const bot = readRepoFile("discord-bot", "src", "index.js");
test("the dragonroll command carries assign and unassign with a character choice", () => {
assert.match(commands, /setName\('assign'\)[\s\S]*setName\('character'\)[\s\S]*setRequired\(true\)[\s\S]*setAutocomplete\(true\)/);
assert.match(commands, /setName\('unassign'\)[\s\S]*setName\('character'\)[\s\S]*setAutocomplete\(true\)/);
// The unassign character is optional, so a player can free their own without naming it.
const unassign = /setName\('unassign'\)([\s\S]*)$/.exec(commands)?.[1] ?? "";
assert.doesNotMatch(unassign, /setRequired\(true\)/);
});
test("the bot client calls the new routes and answers the new subcommands", () => {
assert.match(api, /\/actors\/assign/);
assert.match(api, /\/actors\/unassign/);
assert.match(bot, /\['assign', 'unassign'\]\.includes\(subcommand\)/);
assert.match(bot, /dragonroll\.assignActor\(guildId/);
assert.match(bot, /dragonroll\.unassignActor\(guildId/);
});
test("the character choices autocomplete both new subcommands", () => {
const autocomplete = /if \(interaction\.commandName === 'dragonroll'\) \{([\s\S]*?)\n \}\n/.exec(bot)?.[1] ?? "";
assert.match(autocomplete, /\['assign', 'unassign'\]\.includes\(subcommand\)/);
assert.match(autocomplete, /respondActorChoices\(interaction, guildId\)/);
});
test("the roster shows the player and the status card shows your character", () => {
assert.match(bot, /actor\.discordUserId \? ` 🎮 <@\$\{actor\.discordUserId\}>`/);
assert.match(bot, /name: 'Your character'/);
});
test("the actor model holds one Discord player per character and per campaign", () => {
const model = readRepoFile("backend", "src", "models", "Actor.js");
assert.match(model, /discordUserId: \{ type: String, default: null \}/);
assert.match(model, /\{ campaign: 1, discordUserId: 1 \},\s*\{ unique: true, partialFilterExpression: \{ discordUserId: \{ \$type: 'string' \} \} \}/);
});
}
assignmentRouteTests();
assignmentGuardTests();
botWiringTests();

View File

@@ -0,0 +1,385 @@
// Tests for the sidebar's "force import from Foundry" button (Syndria98/dragonroll#77):
// right-clicking an actor or an item offers to pull the whole actor list or item
// directory of the linked world over. The campaign asks its own backend, which reads
// the world's snapshot off the bridge and writes every document through the writers a
// sync push uses — so a row the campaign already holds is written over instead of
// imported a second time, and the answer counts the rows it made apart from the ones it
// wrote over, which is what the confirmation toast says.
//
// The repository root installs no dependencies, so nothing here is required the way the
// backend itself does it. The import route runs in a stubbed `require` against a fake
// bridge and fake writers, and those writers are then loaded for real and run against
// fake models, like tests/item-folder-sync.test.js does. The sidebar is a Vue component
// this repository cannot build, so its checks read the source, like
// tests/item-sheet-window.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 vm = require("node:vm");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const repoRequire = (relative) => require(path.join(__dirname, "..", relative));
const sidebarSource = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
// --- The import route, against a fake bridge and fake writers ---------------------
const LINKED_CAMPAIGN = { _id: "campaign-1", id: "campaign-1", foundryWorldId: "world-1" };
// What the bridge answers for a whole list: the bridge wraps what the world published
// in `{status, data, world}`, and the route unwraps `data` again.
function bridgeSnapshot(data, world = { id: "world-1", title: "Curse of Strahd" }) {
return { status: 200, data: { status: "ok", data, world, syncedAt: "2026-10-15T10:00:00.000Z" } };
}
// The foundry route with every require stubbed. `campaign` is what the caller owns
// (`null` for a campaign that is not theirs), `answers` maps the bridge path to its
// answer — an Error stands for a bridge that cannot be reached — and `mapping` says
// what a world document becomes in the campaign: a new row or one it already had.
function loadImportRoute({
campaign = LINKED_CAMPAIGN,
answers = {},
mapping = () => ({ created: true }),
} = {}) {
const routes = new Map();
const router = {
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
};
const asked = { bridgePaths: [], campaignFilters: [] };
const written = { actors: [], items: [] };
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id === "../services/foundry") {
return {
requestFoundry: async (bridgePath) => {
asked.bridgePaths.push(bridgePath);
const answer = answers[bridgePath];
if (answer instanceof Error) throw answer;
// A bridge with nothing to answer is one no GM client has published to.
return answer ?? { status: 503, data: { status: "error", msg: "foundry.not-ready" } };
},
};
}
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../models/Campaign") {
return {
findOne: (filter) => {
asked.campaignFilters.push(filter);
const query = { select: () => query, lean: () => Promise.resolve(campaign ?? null) };
return query;
},
};
}
if (id === "./foundry-link") {
return {
saveFoundryActor: async (own, source) => { written.actors.push(source); return mapping(source); },
saveFoundryItem: async (own, source) => { written.items.push(source); return mapping(source); },
};
}
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", "foundry.js"), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
async function importFrom(body, user = { id: "user-1" }) {
const handlers = routes.get("POST /import");
assert.ok(handlers, "POST /import is not mounted");
const res = { payload: null, json(payload) { this.payload = payload; } };
await handlers[handlers.length - 1]({ body, user }, res);
return res.payload;
}
return { importFrom, asked, written };
}
const TWO_ACTORS = [
{ _id: "actor-1", name: "Thalia", type: "character" },
{ _id: "actor-2", name: "Grimnir", type: "npc" },
];
test("the import pulls the world's actors and counts them new against updated", async () => {
const route = loadImportRoute({
answers: { "api/actors": bridgeSnapshot(TWO_ACTORS) },
mapping: (source) => ({ created: source._id === "actor-2" }),
});
const response = await route.importFrom({ campaign: "campaign-1", kind: "actors" });
assert.deepEqual(route.asked.bridgePaths, ["api/actors"], "the actors are read off the bridge");
assert.deepEqual(route.asked.campaignFilters[0], { _id: "campaign-1", createdBy: "user-1" },
"only the campaign the caller holds is imported");
assert.deepEqual(route.written.actors.map((source) => source.name), ["Thalia", "Grimnir"]);
assert.deepEqual(response, { status: "ok", kind: "actors", imported: 1, updated: 1 });
});
test("the item import pulls the world's item directory", async () => {
const route = loadImportRoute({
answers: { "api/items": bridgeSnapshot([{ _id: "item-1", name: "Longsword", type: "weapon" }]) },
});
const response = await route.importFrom({ campaign: "campaign-1", kind: "items" });
assert.deepEqual(route.asked.bridgePaths, ["api/items"], "the bridge's world items, not its actors");
assert.equal(route.written.items.length, 1);
assert.equal(route.written.actors.length, 0);
assert.deepEqual(response, { status: "ok", kind: "items", imported: 1, updated: 0 });
});
test("only the actor and item lists can be imported", async () => {
for (const kind of [undefined, "maps", "notes", "everything"]) {
const route = loadImportRoute();
const response = await route.importFrom({ campaign: "campaign-1", kind });
assert.equal(response.msg, "errors.missing-data", `"${kind}" is not a list to import`);
assert.deepEqual(route.asked.bridgePaths, [], "nothing is asked of the bridge for it");
}
});
test("a campaign the caller does not hold is not imported", async () => {
const route = loadImportRoute({ campaign: null });
const response = await route.importFrom({ campaign: "someone-elses-campaign", kind: "actors" });
assert.equal(response.msg, "errors.notfound");
assert.deepEqual(route.asked.bridgePaths, [], "the bridge is not asked for somebody else's world");
});
test("a campaign with no linked world is told so, and nothing is written", async () => {
const route = loadImportRoute({ campaign: { _id: "campaign-1" } });
const response = await route.importFrom({ campaign: "campaign-1", kind: "items" });
assert.equal(response.msg, "foundry.errors.import-not-linked");
assert.deepEqual(route.asked.bridgePaths, []);
assert.deepEqual(route.written.items, []);
});
test("another world's snapshot is not written into the campaign", async () => {
const route = loadImportRoute({
answers: { "api/actors": bridgeSnapshot(TWO_ACTORS, { id: "world-2", title: "Another World" }) },
});
const response = await route.importFrom({ campaign: "campaign-1", kind: "actors" });
assert.equal(response.msg, "foundry.errors.import-world-mismatch");
assert.deepEqual(route.written.actors, [], "the bridge keeps one world's snapshot at a time");
});
test("a bridge that is not there says so instead of importing nothing", async () => {
const notSetUp = loadImportRoute({
answers: { "api/actors": Object.assign(new Error("Foundry API is not configured."), { code: "FOUNDRY_NOT_CONFIGURED" }) },
});
const unreachable = loadImportRoute({ answers: { "api/actors": new Error("ECONNREFUSED") } });
const noSnapshotYet = loadImportRoute(); // answers nothing → the bridge's own 503
for (const route of [notSetUp, unreachable, noSnapshotYet]) {
const response = await route.importFrom({ campaign: "campaign-1", kind: "actors" });
assert.equal(response.msg, "foundry.errors.import-unavailable");
assert.deepEqual(route.written.actors, []);
}
});
test("a world document that maps to nothing is not counted", async () => {
const route = loadImportRoute({
answers: { "api/items": bridgeSnapshot([
{ _id: "item-1", name: "Longsword", type: "weapon" },
{ _id: "spell-1", name: "Magic Missile", type: "spell" },
]) },
// what is not gear maps to nothing, exactly like a sync push skips it
mapping: (source) => (source.type === "spell" ? null : { created: true }),
});
const response = await route.importFrom({ campaign: "campaign-1", kind: "items" });
assert.equal(route.written.items.length, 2, "every world document is offered to the writer");
assert.deepEqual(response, { status: "ok", kind: "items", imported: 1, updated: 0 });
});
// --- The writers, against fake models: existing rows are written over, not doubled ---
function mongooseQuery(value) {
const result = {
select: () => result,
sort: () => result,
limit: (count) => mongooseQuery(value.slice(0, count)),
lean: () => Promise.resolve(value),
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
};
return result;
}
// Enough of the query language the writers use: equality, $or and $exists.
function matches(document, filter = {}) {
return Object.entries(filter).every(([key, expected]) => {
if (key === "$or") return expected.some((part) => matches(document, part));
const value = document?.[key];
if (expected && typeof expected === "object" && !Array.isArray(expected)) {
return Object.entries(expected).every(([operator, wanted]) => {
if (operator === "$exists") return (value !== undefined && value !== null) === wanted;
throw new Error(`filter operator "${key}.${operator}" is not stubbed`);
});
}
return String(value ?? "") === String(expected ?? "");
});
}
function fakeModel(table, seed = [], campaignId) {
const rows = [];
let counter = 0;
function Document(data = {}) {
counter += 1;
this._id = `${table}-${counter}`;
this.isNew = true;
this.foundryNames = [];
Object.assign(this, data);
}
Document.prototype.save = async function save() {
if (this.isNew) rows.push(this);
this.isNew = false;
return this;
};
Object.defineProperty(Document.prototype, "id", { get() { return this._id; } });
for (const data of seed) {
const row = new Document({ campaign: campaignId, ...data });
row.isNew = false;
rows.push(row);
}
const model = function Model(data) { return new Document(data); };
model.rows = rows;
model.findOne = async (filter) => rows.find((row) => matches(row, filter)) ?? null;
model.find = (filter) => mongooseQuery(rows.filter((row) => matches(row, filter)));
return model;
}
// The sync route loaded for its writers: the same functions the world's pushes and the
// campaign's import run through, here against rows the campaign already holds.
function loadFoundryWriters({ seed = {} } = {}) {
const campaign = { _id: "campaign-1", id: "campaign-1", foundryWorldId: "world-1" };
const seeded = (rows = []) => rows.map((row) => ({ campaign: campaign._id, ...row }));
const models = {
"../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: () => ({ get: () => {}, post: () => {} }) };
if (id.startsWith("node:")) return require(id);
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 repoRequire(path.join("backend", "src", "services", "actor-foundry.js"));
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", "foundry-link.js"), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
return { campaign, models, writers: moduleStub.exports };
}
test("the writers a sync push uses are the ones an import writes through", () => {
const { writers } = loadFoundryWriters();
assert.equal(typeof writers.saveFoundryActor, "function");
assert.equal(typeof writers.saveFoundryItem, "function");
});
test("an imported actor the campaign already has is written over, not made again", async () => {
const sync = loadFoundryWriters({
seed: { actors: [{ _id: "actor-1", name: "Thalia the old", foundryActorId: "actor-1", level: 1 }] },
});
const worldActor = { _id: "actor-1", name: "Thalia", type: "character", system: { details: { level: 3 } } };
const first = await sync.writers.saveFoundryActor(sync.campaign, worldActor);
const second = await sync.writers.saveFoundryActor(sync.campaign, worldActor);
assert.equal(sync.models["../models/Actor"].rows.length, 1, "the world's actor stands in one row");
assert.equal(first.created, false, "the row was already there");
assert.equal(second.created, false);
assert.equal(sync.models["../models/Actor"].rows[0].name, "Thalia", "a force import writes the world over the row");
assert.equal(sync.models["../models/Actor"].rows[0].level, 3);
});
test("an actor the world has never been seen as becomes one row, and the next import updates it", async () => {
const sync = loadFoundryWriters();
const worldActor = { _id: "actor-9", name: "Grimnir", type: "npc", system: { details: { cr: 2 } } };
const made = await sync.writers.saveFoundryActor(sync.campaign, worldActor);
const again = await sync.writers.saveFoundryActor(sync.campaign, worldActor);
assert.equal(made.created, true, "the first import makes the row");
assert.equal(again.created, false, "the one after it only writes it over");
assert.equal(sync.models["../models/Actor"].rows.length, 1);
assert.equal(sync.models["../models/Actor"].rows[0].foundryActorId, "actor-9");
});
test("a hand-made item folds into the import instead of doubling, and keeps being updated", async () => {
const sync = loadFoundryWriters({
seed: { items: [{ _id: "item-1", name: "Longsword", quantity: 1 }] },
});
const worldItem = { _id: "sword-9", name: "Longsword", type: "weapon", system: { quantity: 4, weight: 3, rarity: "rare" } };
const made = await sync.writers.saveFoundryItem(sync.campaign, worldItem);
const again = await sync.writers.saveFoundryItem(sync.campaign, worldItem);
const rows = sync.models["../models/Item"].rows;
assert.equal(rows.length, 1, "the campaign's own row is the world item's row");
assert.equal(made.created, false, "adopting a row the campaign made is not importing it new");
assert.equal(again.created, false);
assert.equal(rows[0].foundryItemId, "sword-9");
assert.equal(rows[0].quantity, 4, "and the force import writes the world over it");
assert.equal(rows[0].rarity, "rare");
});
// --- The sidebar: the button, and the toast it leaves behind ----------------------
const entryMenu = /function showEntryMenu[\s\S]*?\n\}/.exec(sidebarSource)?.[0] ?? "";
const importer = /async function forceImportFromFoundry[\s\S]*?\n\}/.exec(sidebarSource)?.[0] ?? "";
test("the actor and item rows offer a force import in their right-click menu", () => {
assert.ok(entryMenu, "the sidebar has an entry menu");
assert.match(entryMenu, /if \(entityType === ['"]actor['"] \|\| entityType === ['"]item['"]\)/,
"the offer belongs to the two lists mirroring a world, not the maps");
assert.match(entryMenu, /t\(['"]campaigns\.foundry-import\.run['"]\)/);
assert.match(entryMenu, /action: \(\) => \{ HideContextMenu\(\); forceImportFromFoundry\(entityType\); \}/);
});
test("the import is asked for once, says what landed, and reads the list back", async () => {
assert.ok(importer, "the sidebar has the import");
assert.match(importer, /if \(!campaignId\.value \|\| !section \|\| importingFoundry\.value\) return;/,
"clicking a row again while the world is on its way does not start a second import");
assert.match(importer, /Server\(\)\.post\(['"]\/foundry\/import['"], \{ campaign: campaignId\.value, kind: section \}\)/);
assert.match(importer, /DisplayToast\(['"]green['"], t\(['"]campaigns\.foundry-import\.done['"]/);
assert.match(importer, /imported: response\.data\.imported \?\? 0/);
assert.match(importer, /updated: response\.data\.updated \?\? 0/);
assert.match(importer, /await fetchCampaignEntries\(section\)/, "what arrived is read back into the list");
// the failed import says what the backend said, the way the other windows do
assert.match(importer, /DisplayToast\(['"]red['"], t\(response\.data\.msg \|\| ['"]campaigns\.foundry-import\.error['"]\)/);
});
test("every locale has the strings of the button, its toast and its errors", () => {
for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
for (const key of ["run", "done", "error"]) {
assert.ok(campaigns["foundry-import"]?.[key], `${locale} is missing campaigns.foundry-import.${key}`);
}
const foundry = JSON.parse(read("frontend", "i18n", "locales", locale, "foundry.json"));
for (const key of ["import-not-linked", "import-unavailable", "import-world-mismatch"]) {
assert.ok(foundry.errors?.[key], `${locale} is missing foundry.errors.${key}`);
}
}
});

View File

@@ -0,0 +1,239 @@
// 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 foundryService = require(path.join(__dirname, "..", "backend", "src", "services", "foundry"));
const http = require("node:http");
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['"] \}\)/);
});
// --- The bridge the backend reads the icon library through (issue #74) --------
//
// The icon window reaches the world's `icons/` folder through the backend, which
// in turn reads the bridge that the world already pushes its snapshot to. When
// that push works the campaign reads as connected, so a read that still reports
// the bridge as unset is the bug this guards against.
// Set the bridge environment for one call and put it back exactly as it was.
function withBridgeEnv(env, run) {
const keys = ["FOUNDRY_API_URL", "FOUNDRY_API_CLIENT_URL", "FOUNDRY_API_TOKEN"];
const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
for (const key of keys) {
if (env[key] === undefined) delete process.env[key];
else process.env[key] = env[key];
}
return Promise.resolve()
.then(run)
.finally(() => {
for (const key of keys) {
if (saved[key] === undefined) delete process.env[key];
else process.env[key] = saved[key];
}
});
}
test("a connected world answers icon reads through the bridge set under the client URL", async () => {
// A world that connects and syncs is often configured with FOUNDRY_API_CLIENT_URL
// alone — the address its own client reaches. The backend read falls back to it,
// so the icon window is not told its bridge is unset while the world is right there.
const answers = [];
const bridge = http.createServer((request, response) => {
answers.push(request.url);
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify({ status: "ok", dir: "icons", directories: ["icons/svg"], files: [], offset: 0, next: null }));
});
await new Promise((resolve) => bridge.listen(0, "127.0.0.1", resolve));
const clientUrl = `http://127.0.0.1:${bridge.address().port}/`;
try {
const result = await withBridgeEnv(
{ FOUNDRY_API_URL: undefined, FOUNDRY_API_CLIENT_URL: clientUrl, FOUNDRY_API_TOKEN: "read-token" },
() => foundryService.requestFoundry("api/icons?dir=icons&offset=0&limit=120"),
);
assert.equal(result.status, 200);
assert.equal(result.data.status, "ok");
assert.equal(answers.length, 1);
assert.match(answers[0], /^\/api\/icons\?/);
} finally {
await new Promise((resolve) => bridge.close(resolve));
}
});
test("without a bridge under either name a read says it is not configured", async () => {
const error = await withBridgeEnv(
{ FOUNDRY_API_URL: undefined, FOUNDRY_API_CLIENT_URL: undefined, FOUNDRY_API_TOKEN: undefined },
() => foundryService.requestFoundry("api/icons?dir=icons").then(() => null, (err) => err),
);
assert.equal(error?.code, "FOUNDRY_NOT_CONFIGURED");
});
test("the icon window says what actually failed instead of always blaming the bridge", () => {
// axios rejects a non-2xx answer, so the catch reads the route's own i18n key
// off the response: a campaign with no world address is told as much rather
// than as a bridge that is not set up.
assert.match(foundryIconsSource, /requestError\.response\?\.data\?\.msg/);
assert.match(foundryIconsSource, /requestError\.response\?\.data\?\.msg \|\| ['"]foundry\.errors\.icons-unavailable['"]/);
});
// --- 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}`);
}
}
});

View File

@@ -57,7 +57,7 @@ function matches(document, filter = {}) {
}); });
} }
function fakeModel(table, seed = []) { function fakeModel(table, seed = [], campaignId) {
const rows = []; const rows = [];
let counter = 0; let counter = 0;
@@ -76,7 +76,9 @@ function fakeModel(table, seed = []) {
Object.defineProperty(Document.prototype, "id", { get() { return this._id; } }); Object.defineProperty(Document.prototype, "id", { get() { return this._id; } });
for (const data of seed) { for (const data of seed) {
const row = new Document({ [table === "folder" ? "target" : "name"]: undefined, ...data }); // A seeded row belongs to the campaign the requests are made against unless the
// seed says otherwise: the routes scope every lookup by campaign.
const row = new Document({ campaign: campaignId, [table === "folder" ? "target" : "name"]: undefined, ...data });
row.isNew = false; row.isNew = false;
rows.push(row); rows.push(row);
} }
@@ -297,6 +299,76 @@ 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); assert.equal(sync.models["../models/Item"].rows[0].folder, null);
}); });
// --- Only the world's item directory is listed (Syndria98/dragonroll#67) --------------
// The campaign's item list equals the world's items tab: gear that only an actor
// carries is its inventory (kept on the actor document), not a Dragonroll item.
test("an actor's gear is kept off the campaign's item list", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/snapshot", {
worldId: "world-1",
items: [worldItem()],
// Thalia carries a potion the world's item directory does not hold.
actors: [{
_id: "actor-1",
name: "Thalia",
items: [{ _id: "potion-1", name: "Potion of Healing", type: "consumable", system: { quantity: 2 } }],
}],
});
const names = sync.models["../models/Item"].rows.map((row) => row.name);
assert.deepEqual(names, ["Longsword"], "only the world's item reaches the list, not the actor's potion");
});
test("the campaign's item list is the world's whole item directory", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/snapshot", {
worldId: "world-1",
items: [worldItem(), worldItem({ _id: "item-2", name: "Torch", type: "loot", system: { quantity: 1 } })],
actors: [],
});
assert.deepEqual(
sync.models["../models/Item"].rows.map((row) => row.name).sort(),
["Longsword", "Torch"],
);
});
test("an item carried by a character is listed once, as its world entry", async () => {
const sync = loadSyncRoute();
await sync.call("POST /sync/snapshot", {
worldId: "world-1",
items: [worldItem()],
// The same sword, a second copy embedded in an actor under another id.
actors: [{ _id: "actor-1", name: "Thalia", items: [worldItem({ _id: "sword-copy" })] }],
});
assert.deepEqual(sync.models["../models/Item"].rows.map((row) => row.name), ["Longsword"]);
});
test("a full snapshot prunes gear that only an actor carried", async () => {
const sync = loadSyncRoute({
seed: { items: [{ _id: "potion-1", name: "Potion of Healing", foundryItemId: "embedded-1" }] },
});
// The world's item directory is now empty: nothing but a character holds the potion.
await sync.call("POST /sync/snapshot", {
worldId: "world-1",
items: [],
actors: [{
_id: "actor-1",
name: "Thalia",
items: [{ _id: "embedded-1", name: "Potion of Healing", type: "consumable", system: { quantity: 2 } }],
}],
fullSync: true,
});
assert.deepEqual(sync.models["../models/Item"].rows, [], "the actor's own gear no longer stands in the item list");
});
test("a folder coloured in the world is coloured in the campaign", async () => { test("a folder coloured in the world is coloured in the campaign", async () => {
const sync = loadSyncRoute(); const sync = loadSyncRoute();
@@ -373,9 +445,12 @@ test("every folder listing says which campaign list it belongs to", () => {
// field existed carry none at all. tests/entry-folders.test.js runs these routes. // field existed carry none at all. tests/entry-folders.test.js runs these routes.
for (const route of ["note.js", "folder.js"]) { for (const route of ["note.js", "folder.js"]) {
const source = read("backend", "src", "routes", route); const source = read("backend", "src", "routes", route);
const listings = source.match(/Folder\.find\(/g) ?? []; // The listings that gather a campaign's folders are the ones shown as a section's
// tree. A walk of one folder's own children (`parentFolder`) is inside a single
// list already: folders are only ever nested within their own section.
const listings = source.match(/Folder\.find\(\{\s*campaign/g) ?? [];
assert.ok(listings.length, `${route} lists folders`); assert.ok(listings.length, `${route} lists folders`);
const filtered = source.match(/Folder\.find\(\{[^{]*Folder\.filterForTarget\((?:'note'|target)\)/g) ?? []; const filtered = source.match(/Folder\.find\(\{\s*campaign[^{]*Folder\.filterForTarget\((?:'note'|target)\)/g) ?? [];
assert.equal(filtered.length, listings.length, `${route} has a folder listing that names no campaign list`); assert.equal(filtered.length, listings.length, `${route} has a folder listing that names no campaign list`);
} }
}); });
@@ -725,13 +800,15 @@ test("items are grouped under the folder they stand in, nested", () => {
row.kind, row.kind === "folder" ? row.folder.name : row.item.name, row.depth, row.kind, row.kind === "folder" ? row.folder.name : row.item.name, row.depth,
]); ]);
// Every folder is followed by what stands in it, one step deeper, and the items that
// stand at the root come last (see BuildItemRows).
assert.deepEqual(shape, [ assert.deepEqual(shape, [
["folder", "Melee Weapons", 0], ["folder", "Melee Weapons", 0],
["item", "Longsword", 1],
["folder", "Ranged Weapons", 0], ["folder", "Ranged Weapons", 0],
["folder", "Powder Weapons", 1], ["folder", "Powder Weapons", 1],
["item", "Pistol", 1], ["item", "Pistol", 2],
["item", "Torch", 0], ["item", "Torch", 0],
["item", "Longsword", 1],
]); ]);
}); });
@@ -758,9 +835,9 @@ test("an item whose folder is gone, or a folder nested in itself, reads as a roo
); );
const shape = rows.map((row) => [row.kind, row.kind === "folder" ? row.folder.name : row.item.name]); const shape = rows.map((row) => [row.kind, row.kind === "folder" ? row.folder.name : row.item.name]);
assert.ok(shape.includes(["item", "Torch"]), "the item is not lost with the folder that was removed"); assert.ok(shape.some(([kind, name]) => kind === "item" && name === "Torch"), "the item is not lost with the folder that was removed");
assert.deepEqual(new Set(shape.filter(([kind]) => kind === "folder").map(([, name]) => name)), new Set(["A", "B"])); assert.deepEqual(new Set(shape.filter(([kind]) => kind === "folder").map(([, name]) => name)), new Set(["A", "B"]));
assert.equal(rows.filter(([kind]) => kind === "folder").length, 2, "a broken tree is walked once, not forever"); assert.equal(shape.filter(([kind]) => kind === "folder").length, 2, "a broken tree is walked once, not forever");
}); });
test("every locale labels the folder row", () => { test("every locale labels the folder row", () => {

View File

@@ -0,0 +1,89 @@
// Tests for Syndria98/dragonroll#63: the item rows in the campaign sidebar dropped the text
// listing category, rarity and quantity — the rarity colours the text of the entry instead
// (common white, uncommon green, rare blue, very rare purple, legendary orange) — and the
// quantity left the item surfaces altogether, since it only belongs to an actor's inventory.
//
// The repository root installs no dependencies, so these read the sources the way
// tests/item-entry-display.test.js does — the checks are about the markup and style.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const sidebarSource = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
const itemWindowSource = read("frontend", "app", "components", "windows", "ItemSheetWindow.vue");
const entryFormSource = read("frontend", "app", "components", "windows", "CreateCampaignEntryWindow.vue");
const sheetSource = read("frontend", "app", "components", "windows", "CharacterSheetWindow.vue");
const colorsSource = read("frontend", "app", "assets", "css", "colors.scss");
// The block that renders the item rows, as in tests/item-entry-display.test.js.
const itemSection =
/<template v-else-if="activeSection === 'items'">([\s\S]*?)<\/template>\s*\n\s*<template v-else>/.exec(sidebarSource)?.[1] ?? "";
const rarities = ["common", "uncommon", "rare", "very-rare", "legendary"];
// `selector` is inserted verbatim, so escape the `.` of a class combination. Comments are dropped:
// they explain a rule, they are not part of it.
function ruleFor(selector) {
const rule = new RegExp(`\\.${selector}\\s*\\{([^}]*)\\}`).exec(sidebarSource)?.[0];
return rule?.replace(/\/\*[\s\S]*?\*\//g, "");
}
test("the item entry no longer lists the category, rarity and quantity as text", () => {
assert.ok(itemSection, "expected to find the items section of the sidebar");
assert.doesNotMatch(itemSection, /entity-entry-meta/, "the item row must not render a meta line");
assert.doesNotMatch(itemSection, /campaigns\.item\.(categories|rarities|quantity)/, "the item row must not render item meta text");
assert.doesNotMatch(sidebarSource, /itemSummary/, "the removed summary helper must not be kept around");
});
test("the rarity of an item picks a class for the text of its entry", () => {
assert.match(
itemSection,
/<span class="entity-entry-name" :class="rarityClass\(row\.item\)"/,
"the item name must carry the class picked from its rarity"
);
const helper = /function rarityClass\(item\)\s*\{[\s\S]*?\n\}/.exec(sidebarSource)?.[0] ?? "";
assert.ok(helper, "expected a rarityClass helper");
for (const rarity of rarities) {
assert.ok(helper.includes(`'${rarity}'`), `rarityClass must know about '${rarity}'`);
}
});
test("each rarity colours the entry text with its own theme colour", () => {
for (const rarity of rarities) {
const rule = ruleFor(`entity-entry-name\\.rarity-${rarity}`);
assert.ok(rule, `expected a colour rule for .entity-entry-name.rarity-${rarity}`);
assert.match(rule, new RegExp(`color:\\s*var\\(--color-rarity-${rarity}\\)`));
}
});
test("both theme maps carry the rarity colours", () => {
for (const rarity of rarities) {
const declarations = colorsSource.match(new RegExp(`rarity-${rarity}:\\s*#[0-9a-fA-F]{6}`, "g")) || [];
assert.equal(declarations.length, 2, `expected rarity-${rarity} in both the dark and the light map`);
}
});
test("the quantity only shows in an actor's inventory", () => {
assert.doesNotMatch(itemWindowSource, /quantity/, "the item window must not list the quantity");
assert.doesNotMatch(entryFormSource, /quantity/, "the item create/edit form must not offer the quantity");
// the character sheet's inventory table keeps it.
assert.match(sheetSource, /campaigns\.character-sheet\.quantity/);
assert.match(sheetSource, /\{\{ item\.quantity \}\}/);
});
test("no locale keeps the removed item quantity strings", () => {
for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
assert.ok(campaigns.item, `${locale} is missing the campaigns.item block`);
assert.equal(campaigns.item.quantity, undefined, `${locale} still has campaigns.item.quantity`);
assert.equal(campaigns.item["quantity-short"], undefined, `${locale} still has campaigns.item.quantity-short`);
// the character sheet's inventory keeps its own quantity column label
assert.ok(campaigns["character-sheet"]?.quantity, `${locale} is missing campaigns.character-sheet.quantity`);
}
});

View File

@@ -66,19 +66,22 @@ test("the item routes accept the icon and upload one", () => {
test("the item info window is registered and opens on a sidebar click", () => { test("the item info window is registered and opens on a sidebar click", () => {
assert.match(windowDefsSource, /item_sheet:\s*{\s*title:[^}]*ItemSheetWindow\.vue/s); assert.match(windowDefsSource, /item_sheet:\s*{\s*title:[^}]*ItemSheetWindow\.vue/s);
// clicking (or Enter/Space on) an item row opens the window instead of expanding inline. // clicking (or Enter/Space on) an item row opens the window instead of expanding inline.
// Since #44 the rows come from the folder tree the world synced, so the row holds the item. // The rows come from the item list's folder tree, so the row holds the item.
assert.match(sidebarSource, /v-for="row in itemRows"[\s\S]*?@click="openItemSheet\(row\.item\)"/); assert.match(sidebarSource, /v-for="row in entryRows\.item\.value"[\s\S]*?@click="openItemSheet\(row\.item\)"/);
assert.match(sidebarSource, /CreateWindow\(['"]item_sheet['"],\s*\{ item \}\)/); assert.match(sidebarSource, /CreateWindow\(['"]item_sheet['"],\s*\{ item \}\)/);
assert.doesNotMatch(sidebarSource, /toggleEntryDetails/); assert.doesNotMatch(sidebarSource, /toggleEntryDetails/);
}); });
test("the item window shows the info and offers both icon sources", () => { test("the item window shows the info and offers both icon sources", () => {
// info: name, category, rarity, quantity, weight, properties, description // info: name, category, rarity, weight, properties, description — quantity is gone
for (const key of ["form.name", "form.category", "form.rarity", "form.quantity", "form.weight", "form.properties", "form.description"]) { // (#63 keeps it for the actors' inventories).
for (const key of ["form.name", "form.category", "form.rarity", "form.weight", "form.properties", "form.description"]) {
assert.ok(itemWindowSource.includes(key), `expected the window to render ${key}`); assert.ok(itemWindowSource.includes(key), `expected the window to render ${key}`);
} }
// own icon: upload through the item route like the character sheet does its photo // own icon: #65 moved picking one into a window of its own, which uploads through
assert.match(itemWindowSource, /\/item\/upload-image\?item=/); // 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 // Foundry icon: switch the item image back to the one the world sent
assert.match(itemWindowSource, /form\.value\.foundryImage/); assert.match(itemWindowSource, /form\.value\.foundryImage/);
assert.match(itemWindowSource, /updateItem\(\{ image: form\.value\.foundryImage \}\)/); assert.match(itemWindowSource, /updateItem\(\{ image: form\.value\.foundryImage \}\)/);

View File

@@ -85,6 +85,9 @@ function loadMapRoutes({ ownsCampaign = true, maps = [], notes = [] } = {}) {
}, },
// The pins do not ask after actors, only the token routes below do. // The pins do not ask after actors, only the token routes below do.
"../models/Actor": { findOne: () => mongooseQuery(null) }, "../models/Actor": { findOne: () => mongooseQuery(null) },
// The map list's own folder tree: `/list` reads it and `/update` checks a move
// against it, so the pins need the model to answer, never what it answers.
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
}); });
} }
@@ -181,7 +184,12 @@ function loadNoteRoutes({ ownsCampaign = true, notes = [], folders = [], deleted
findById: (id) => mongooseQuery(notes.find((note) => note._id === id) ?? null), findById: (id) => mongooseQuery(notes.find((note) => note._id === id) ?? null),
deleteOne: () => mongooseQuery({ deletedCount }), deleteOne: () => mongooseQuery({ deletedCount }),
}, },
"../models/Folder": { find: () => mongooseQuery(folders) }, "../models/Folder": {
find: () => mongooseQuery(folders),
// models/Folder.js: the note tree is every folder that is not one of the other
// campaign lists, whose rows carry no target at all.
filterForTarget: (target) => (target === "note" ? { target: { $nin: ["actor", "item", "map"] } } : { target }),
},
"../models/Map": { "../models/Map": {
// The driver drops the pins of the note from every map holding one; what is worth // The driver drops the pins of the note from every map holding one; what is worth
// keeping here is the filter it is asked to do that with. // keeping here is the filter it is asked to do that with.

View File

@@ -82,6 +82,9 @@ function loadMapRoutes({ ownsCampaign = true, maps = [], actors = [] } = {}) {
: null : null
), ),
}, },
// The map list's own folder tree: `/list` reads it and `/update` checks a move
// against it, so the tokens need the model to answer, never what it answers.
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
}); });
} }
@@ -188,6 +191,8 @@ function loadActorRoutes({ ownsCampaign = true, actors = [], deletedCount = 1 }
return { modifiedCount: 1 }; return { modifiedCount: 1 };
}, },
}, },
// The actor list's own folder tree, which the delete does not ask after.
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
}); });
return { api, tokensPulled }; return { api, tokensPulled };
} }
@@ -299,10 +304,14 @@ function mapViewerTokenWiringTests() {
const sidebar = readRepoFile("frontend", "app", "components", "partials", "ContentSidebar.vue"); const sidebar = readRepoFile("frontend", "app", "components", "partials", "ContentSidebar.vue");
test("an actor row of the sidebar can be dragged out of it", () => { test("an actor row of the sidebar can be dragged out of it", () => {
const actorRow = /<div v-for="actor in actors"[^>]*>/.exec(sidebar)?.[0]; // The actors' block of the sidebar: since the entry lists got their folders the rows
// come from that tree, so the actor row holds its actor as `row.item`.
const actorSection = /<template v-else-if="activeSection === 'actors'">([\s\S]*?)<\/template>\s*\n\s*<template v-else-if="activeSection === 'items'">/
.exec(sidebar)?.[1] ?? "";
const actorRow = /<div v-else class="entity-entry"[^>]*>/.exec(actorSection)?.[0];
assert.ok(actorRow, "expected the actor rows of the sidebar"); assert.ok(actorRow, "expected the actor rows of the sidebar");
assert.match(actorRow, /draggable="true"/); assert.match(actorRow, /draggable="true"/);
assert.match(actorRow, /@dragstart="startActorDrag\(\$event, actor\)"/); assert.match(actorRow, /@dragstart="startActorDrag\(\$event, row\.item\)"/);
assert.match(sidebar, /setData\(ACTOR_DRAG_TYPE, String\(actor\._id\)\)/); assert.match(sidebar, /setData\(ACTOR_DRAG_TYPE, String\(actor\._id\)\)/);
}); });

View File

@@ -0,0 +1,72 @@
// Tests for Syndria98/dragonroll#71: `pnpm dev` warned, on every frontend build,
// "You probably don't mean to use the color value red in interpolation here" from `theme-vars()`
// in colors.scss. `red`, `green` and `gray` are also Sass colour keywords, so as unquoted map keys
// they were parsed as colour *values* and interpolating one into `--color-#{$name}` warned (and can
// emit an invalid name). Quoting those keys keeps them strings; the emitted CSS is unchanged, so
// `var(--color-red)` and friends still resolve.
//
// `sass` is not installed for `npm test`, so this reads colors.scss the way the other tests read
// sources: the check is that no map key is left bare when it spells a CSS colour keyword.
//
// 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 colorsSource = read("frontend", "app", "assets", "css", "colors.scss");
// The CSS named colours. Sass parses any of these (in any case) as a colour value, so a theme or
// accent map key spelled like one of them has to be quoted to stay a string.
const colorKeywords = new Set(
[
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black",
"blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse",
"chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan",
"darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
"darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue",
"darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray",
"dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
"gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred",
"indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon",
"lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen",
"lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
"lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon",
"mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen",
"mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue",
"mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab",
"orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise",
"palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple",
"rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown",
"seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow",
"springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "transparent", "turquoise",
"violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen",
]
);
// The keys of the `$themes` and `$accents` maps and of each theme inside them: a line starting with
// `key:` or `"key":`. The custom properties of the mixins (`--color-#{$name}: #{$value};`) do not
// match, `#` is not part of a key.
const mapKeys = [...colorsSource.matchAll(/^\s*("[^"]+"|[A-Za-z][A-Za-z0-9_-]*)\s*:/gm)].map((m) => m[1]);
test("the theme and accent maps are read as maps of keys", () => {
// sanity check on the extraction above before it is trusted to find a bare colour keyword
for (const key of ["dark", "light", "katlum", "solus", "silang", "background", "text"]) {
assert.ok(mapKeys.includes(key), `expected to find the map key '${key}'`);
}
});
test("no map key is a bare CSS colour keyword", () => {
const bare = mapKeys.filter((key) => !key.startsWith('"') && colorKeywords.has(key.toLowerCase()));
assert.deepEqual(bare, [], `quote these colors.scss map keys so Sass keeps them strings: ${bare.join(", ")}`);
});
test("the colour-named theme keys are quoted in both maps", () => {
for (const [key, value] of [["red", "#e06c75"], ["green", "#98c379"], ["gray", "#cccccc"]]) {
const declarations = colorsSource.match(new RegExp(`"${key}":\\s*${value}\\b`, "g")) || [];
assert.equal(declarations.length, 2, `expected quoted "${key}": ${value} in both the dark and the light map`);
}
});