Things
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m6s

This commit is contained in:
2026-10-13 22:50:51 +02:00
parent 50828af674
commit af76cf1050
18 changed files with 847 additions and 86 deletions

View File

@@ -74,14 +74,21 @@ backend/src/
├── index.js app bootstrap: dotenv, static uploads, json limits (50mb), ├── index.js app bootstrap: dotenv, static uploads, json limits (50mb),
│ passport init, CORS, route mounting, listen(5000) │ passport init, CORS, route mounting, listen(5000)
├── db.js connectDB() -> mongoose.connect(process.env.DB_URI) ├── db.js connectDB() -> mongoose.connect(process.env.DB_URI)
├── models/ User.js Campaign.js Note.js Folder.js ├── models/ User.js Campaign.js Note.js Folder.js Actor.js Item.js
├── routes/ user.js campaign.js note.js folder.js │ FoundryLinkRequest.js DiscordLinkRequest.js DiscordGuildLink.js
├── routes/ user.js campaign.js note.js folder.js actor.js item.js
│ foundry-link.js (token sync, mounted BEFORE auth) foundry.js (bridge proxy)
│ discord.js
├── services/ ├── services/
│ ├── keys.js { secret: "putyoursecrethere" } <- JWT secret, hardcoded │ ├── keys.js { secret: "putyoursecrethere" } <- JWT secret, hardcoded
│ ├── passport.js JwtStrategy: Bearer token -> User.findById(jwt_payload._id) │ ├── passport.js JwtStrategy: Bearer token -> User.findById(jwt_payload._id)
│ ├── middleware.js isAdmin — imported by routes/user.js but applied to no route yet │ ├── middleware.js isAdmin — imported by routes/user.js but applied to no route yet
│ ├── rate-limiter.js express-rate-limit: 150 req / 60 min, applied to /user/login and /user/setup │ ├── rate-limiter.js express-rate-limit: 150 req / 60 min, applied to /user/login and /user/setup
│ └── storage.js multer diskStorage -> backend/src/uploads/, filename `<field>-<timestamp><ext>` │ ├── storage.js multer diskStorage -> backend/src/uploads/, filename `<field>-<timestamp><ext>`
│ ├── foundry.js requestFoundry(): reads the optional snapshot bridge
│ ├── foundry-fields.js shared asText/numberOr/plainText/stringList for the mappers
│ ├── actor-foundry.js foundryActorToCharacter(): Foundry actor document -> Actor fields
│ └── item-foundry.js foundryItemToItemData(): Foundry item document -> Item fields
└── uploads/ created on demand, gitignored, served PUBLICLY at /api/public └── uploads/ created on demand, gitignored, served PUBLICLY at /api/public
``` ```
@@ -94,7 +101,9 @@ backend/src/
`/get-settings`). `/get-settings`).
3. `checkAuth = passport.authenticate('jwt', { session: false })` — note the **missing declaration** 3. `checkAuth = passport.authenticate('jwt', { session: false })` — note the **missing declaration**
(implicit global). Everything mounted after this is JWT-protected. (implicit global). Everything mounted after this is JWT-protected.
4. `/api/campaign`, `/api/note`, `/api/folder`. 4. `/api/campaign`, `/api/note`, `/api/folder`, `/api/actor`, `/api/item` and `/api/foundry`
(the read-only bridge proxy). `routes/foundry-link.js` is deliberately mounted **before** step 3 —
it authenticates with the per-campaign sync token instead of a Dragonroll login (see §4.1).
JWT: signed in `POST /api/user/login` with payload `{ _id, username, name, email, admin, settings }`, JWT: signed in `POST /api/user/login` with payload `{ _id, username, name, email, admin, settings }`,
`expiresIn: 172800` (48h). `req.user` is the Mongoose `User` document, so routes use `req.user.id`. `expiresIn: 172800` (48h). `req.user` is the Mongoose `User` document, so routes use `req.user.id`.
@@ -130,14 +139,18 @@ Ownership is enforced per handler. `settings`, `color`, `description` and `User.
``` ```
User ──< Campaign ──< Note ──?> Folder ──?> Folder (parentFolder, self-ref) User ──< Campaign ──< Note ──?> Folder ──?> Folder (parentFolder, self-ref)
└───────< Folder └───────< Folder
└───────< Actor (Foundry actors, when linked)
└───────< Item (Foundry gear + hand-made items)
``` ```
| Model | File | Fields | | Model | File | Fields |
|---|---|---| |---|---|---|
| `User` | `models/User.js` | `name*`, `username*` (unique), `email*` (unique), `password` (bcrypt hash, 10 salt rounds), `date`, `admin` (bool, default false), `image`, `setupCode`, `settings` (Object) | | `User` | `models/User.js` | `name*`, `username*` (unique), `email*` (unique), `password` (bcrypt hash, 10 salt rounds), `date`, `admin` (bool, default false), `image`, `setupCode`, `settings` (Object) |
| `Campaign` | `models/Campaign.js` | `name*`, `description`, `color`, `createdBy*` → User, `date`, `settings` (Object) | | `Campaign` | `models/Campaign.js` | `name*`, `description`, `color`, `createdBy*` → User, `date`, `settings` (Object), `foundryWorldId` (unique, sparse), `foundryWorldTitle`, `foundrySystem`, `foundrySyncTokenHash` (`select: false`), `discordGuildId` |
| `Note` | `models/Note.js` | `title`, `content` (markdown source string), `campaign*` → Campaign, `folder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` | | `Note` | `models/Note.js` | `title`, `content` (markdown source string), `campaign*` → Campaign, `folder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` |
| `Folder` | `models/Folder.js` | `name*`, `campaign*` → Campaign, `parentFolder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` | | `Folder` | `models/Folder.js` | `name*`, `campaign*` → Campaign, `parentFolder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` |
| `Actor` | `models/Actor.js` | `name*`, `type` (`character`\|`npc`\|`creature`), `species`, `className`, `subclass`, `level`, `background`, `challengeRating`, `description`, `image`, `abilityScores{str..cha}`, `armorClass`, `speed`, `proficiencies`, `inventory[{name,quantity,weight}]` (flattened Foundry items, embedded — not `Item` docs), `traits`, `spells` (newline text), `campaign*` → Campaign, `foundryActorId` (unique per campaign), `date` |
| `Item` | `models/Item.js` | `name*`, `category` (`weapon`\|`armor`\|`shield`\|`adventuring-gear`\|`magic-item`\|`consumable`\|`tool`\|`treasure`\|`other`), `rarity` (`common`…`artifact`), `quantity`, `weight`, `properties`, `description`, `campaign*` → Campaign, `foundryItemId` (unique per campaign), `foundryNames` (names Foundry uses for it, keeps dedup stable across a Dragonroll rename), `date` |
`*` = required. Notes and folders are ordered by `date: -1` everywhere. `*` = required. Notes and folders are ordered by `date: -1` everywhere.
@@ -183,6 +196,54 @@ subfolders re-parented to null then deleted.
`GET /api/test` — health check. `GET /api/test` — health check.
`GET /api/actor/list?campaign=` → `{status:'ok',actors}`
`POST /api/actor/create` — `{name*,campaign*,type?,species?,className?,subclass?,level?,background?,challengeRating?,description?}`
`POST /api/actor/update` — `{id*, name?, species?, className?, subclass?, level?, abilityScores?, armorClass?, speed?, proficiencies?, inventory?, traits?, spells?, image?}` — partial, ownership checked
`POST /api/actor/upload-image?actor=` — multipart field `image`
`POST /api/actor/delete` — `{id}`
`GET /api/item/list?campaign=` → `{status:'ok',items}`
`POST /api/item/create` — `{name*,campaign*,category?,rarity?,quantity?,weight?,properties?,description?}`
`POST /api/item/update` — `{id*, name?, category?, rarity?, quantity?, weight?, properties?, description?}` — partial, ownership checked. `''` for `quantity`/`weight` is ignored, like `/item/create`.
`POST /api/item/delete` — `{id}`
### 4.1 Foundry integration (actors, items)
`dragonroll-foundry/` holds the Foundry VTT module (`scripts/api.js`, loaded by `module.json`) and an
optional read-only snapshot bridge (`bridge/server.js`). The module talks to Dragonroll with a
per-campaign bearer token, **not** a Dragonroll login: `POST /api/foundry/link/complete` redeems a
pairing code, stores its hash on `Campaign.foundrySyncTokenHash` and hands the plain token to Foundry
once. Every sync route re-reads the campaign from that hash and rejects payloads whose `worldId` is
not `Campaign.foundryWorldId` (`syncCampaign` / `requestMatchesWorld`). CORS is opened for
`/api/foundry/sync*` and `/foundry/link/complete` in `src/index.js`, before the app-wide CORS.
`dragonroll-foundry/README.md` documents pairing, the bridge and its environment variables.
| Sync route (token) | Meaning |
|---|---|
| `POST /sync/snapshot` | `{worldId, actors[], items[], fullSync}` — upserts actors, world items and every item embedded in those actors; a `fullSync` also deletes actors/items that are gone |
| `POST /sync/item-snapshot` | `{worldId, items[]}` — live world-item edits, upsert only (never prunes) |
| `POST /sync/item-delete` | `{worldId, foundryItemId}` — a world item was deleted |
| `GET /sync/characters` | Actors the module applies back into Foundry |
| `GET /sync/items` | Items the module applies back into Foundry (creates world items for Dragonroll-authored ones) |
| `POST /sync/map` / `POST /sync/map-item` | Store the id mapping after the module creates a document |
| `POST /sync/delete` | `{worldId, foundryActorId}` |
Rules worth knowing before editing this:
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index so local
documents can leave it unset). A document carrying the `dragonroll-foundry.actorId` /
`dragonroll-foundry.itemId` flag adopts the matching Dragonroll row.
- **Items are deduplicated by name.** Foundry keeps the same gear once per carrier, so one Dragonroll
`Item` per name: the first document to claim it keeps the mapping, later copies just return it.
`foundryNames` remembers Foundry's names so a Dragonroll rename does not resurrect a duplicate.
`services/item-foundry.js` returns `null` for non-gear types (spells, classes, feats, species…),
which the sync skips.
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events
overwrite. Item pruning requires the full snapshot, since only it sees world items and actor copies.
- `Actor.inventory` stays a flattened copy of the actor's embedded items; it is not linked to `Item`.
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only
bridge, only useful when `FOUNDRY_API_URL` is configured.
## 5. Frontend ## 5. Frontend
``` ```

View File

@@ -15,7 +15,7 @@ An open-source helper for role-playing games
# Dragonroll # Dragonroll
Dragonroll is an open source helper for role-playing games. Dragonroll is an open source connector for role-playing games.
## Features ## Features
@@ -48,4 +48,21 @@ or
./start-dev.sh ./start-dev.sh
``` ```
if you want to start the development environments if you want to start the development environments
## TODO
- Dragonroll <-> Foundry integration
- Dragonroll <-> Discord Bot integration
- Dragonroll <-> Obsidian integration
What to sync:
- Actors
- Monsters
- Items
- Notes
- Maps
- Music ?

View File

@@ -22,7 +22,17 @@ const ItemSchema = new Schema({
ref: 'Campaign', ref: 'Campaign',
required: true required: true
}, },
foundryItemId: { type: String },
// Names Foundry uses for this item. Dragonroll may rename it, and the copies
// Foundry keeps sending still have to fold into this row instead of
// creating a second item under their original name.
foundryNames: { type: [String], default: [] },
date: { type: Date, default: Date.now } date: { type: Date, default: Date.now }
}); });
ItemSchema.index(
{ campaign: 1, foundryItemId: 1 },
{ unique: true, partialFilterExpression: { foundryItemId: { $type: 'string' } } }
);
module.exports = mongoose.model('Item', ItemSchema); module.exports = mongoose.model('Item', ItemSchema);

View File

@@ -6,11 +6,16 @@ const router = express.Router();
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor'); const Actor = require('../models/Actor');
const Item = require('../models/Item');
const FoundryLinkRequest = require('../models/FoundryLinkRequest'); const FoundryLinkRequest = require('../models/FoundryLinkRequest');
const { foundryActorToCharacter } = require('../services/actor-foundry'); const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
const linkRateLimit = rateLimit({ windowMs: 15 * 60 * 1000, max: 20 }); const linkRateLimit = rateLimit({ windowMs: 15 * 60 * 1000, max: 20 });
// Upper bound for the Foundry names remembered per synced item (see Item model).
const MAX_FOUNDRY_NAMES = 20;
function codeHash(code) { function codeHash(code) {
return crypto.createHash('sha256').update(String(code ?? '').trim()).digest('hex'); return crypto.createHash('sha256').update(String(code ?? '').trim()).digest('hex');
} }
@@ -67,6 +72,63 @@ async function saveFoundryActor(campaign, source, fullSync = false) {
return { foundryActorId, actorId: actor.id }; return { foundryActorId, actorId: actor.id };
} }
// A snapshot carries world-level items plus the items embedded in every actor it
// sends. World items are listed first so they own a name before its copies.
function snapshotItemSources(body) {
const sources = [];
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) {
const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryItemToItemData(source || {});
if (!foundryItemId || !fields) return null;
let item = await Item.findOne({ campaign: campaign._id, foundryItemId });
const dragonrollItemId = source?.flags?.['dragonroll-foundry']?.itemId;
if (!item && mongoose.isValidObjectId(dragonrollItemId)) {
const flagged = await Item.findOne({ _id: dragonrollItemId, campaign: campaign._id });
// Only adopt a flagged item while no other Foundry document owns its mapping.
if (flagged && (!flagged.foundryItemId || flagged.foundryItemId === foundryItemId)) item = flagged;
}
if (!item) {
// The same gear exists more than once in Foundry: once in the world
// directory and once inside each actor carrying it. Keep a single
// Dragonroll item per name so inventories do not flood the Item list.
const sameName = await Item.find({
campaign: campaign._id,
$or: [{ name: fields.name }, { foundryNames: fields.name }]
}).limit(4);
const represented = sameName.find((candidate) => candidate.foundryItemId);
if (represented) return { foundryItemId, itemId: represented.id };
const unclaimed = sameName.filter((candidate) => !candidate.foundryItemId);
item = unclaimed.length === 1 ? unclaimed[0] : new Item({ campaign: campaign._id, name: fields.name });
}
item.foundryItemId = foundryItemId;
if (!fullSync || item.isNew) Object.assign(item, fields);
if (!item.foundryNames.includes(fields.name)) {
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
}
await item.save();
return { foundryItemId, itemId: item.id };
}
async function syncFoundryItems(campaign, sources, fullSync = false) {
const items = [];
for (const source of sources) {
const mapping = await saveFoundryItem(campaign, source, fullSync);
if (mapping) items.push(mapping);
}
return items;
}
function readWorld(body) { function readWorld(body) {
const world = body?.world; const world = body?.world;
if (!world || typeof world.id !== 'string' || !world.id.trim()) return null; if (!world || typeof world.id !== 'string' || !world.id.trim()) return null;
@@ -178,17 +240,22 @@ router.post('/sync/snapshot', async (req, res) => {
try { try {
const campaign = await syncCampaign(req, res); const campaign = await syncCampaign(req, res);
if (!campaign) return; if (!campaign) return;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.actors)) { const actorSources = Array.isArray(req.body.actors) ? req.body.actors : null;
const itemSources = Array.isArray(req.body.items) ? req.body.items : null;
if (!requestMatchesWorld(campaign, req.body.worldId) || (!actorSources && !itemSources)) {
return res.json({ status: 'error', msg: 'errors.missing-data' }); return res.json({ status: 'error', msg: 'errors.missing-data' });
} }
const fullSync = req.body.fullSync === true;
const actors = []; const actors = [];
for (const source of req.body.actors) { for (const source of actorSources || []) {
const mapping = await saveFoundryActor(campaign, source, req.body.fullSync === true); const mapping = await saveFoundryActor(campaign, source, fullSync);
if (mapping) actors.push(mapping); if (mapping) actors.push(mapping);
} }
if (req.body.fullSync === true) { const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync);
const currentIds = req.body.actors
if (fullSync && actorSources) {
const currentIds = actorSources
.map((source) => String(source?._id || source?.id || '').trim()) .map((source) => String(source?._id || source?.id || '').trim())
.filter(Boolean); .filter(Boolean);
await Actor.deleteMany({ await Actor.deleteMany({
@@ -196,7 +263,35 @@ router.post('/sync/snapshot', async (req, res) => {
foundryActorId: { $exists: true, $nin: currentIds } foundryActorId: { $exists: true, $nin: currentIds }
}); });
} }
res.json({ status: 'ok', actors }); // Pruning needs a full snapshot: only that request sees the world
// directory and every actor's copies at the same time.
if (fullSync && itemSources) {
const currentIds = snapshotItemSources(req.body)
.map((source) => String(source?._id || source?.id || '').trim())
.filter(Boolean);
await Item.deleteMany({
campaign: campaign._id,
foundryItemId: { $exists: true, $nin: currentIds }
});
}
res.json({ status: 'ok', actors, items });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Live Foundry item edits: upserts only, never prunes. Removing items that no
// longer exist is left to the full snapshot sent with the actors.
router.post('/sync/item-snapshot', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items) });
} catch (err) { } catch (err) {
console.error(err); console.error(err);
res.json({ status: 'error', msg: 'errors.internal' }); res.json({ status: 'error', msg: 'errors.internal' });
@@ -255,4 +350,58 @@ router.post('/sync/map', async (req, res) => {
} }
}); });
// Only world-level Foundry items reach this route: an item dropped by an actor
// still exists in the world, and its actor snapshot overwrites the inventory.
router.post('/sync/item-delete', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const foundryItemId = String(req.body.foundryItemId || '').trim();
if (!requestMatchesWorld(campaign, req.body.worldId) || !foundryItemId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
await Item.deleteOne({ campaign: campaign._id, foundryItemId });
res.json({ status: 'ok' });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.get('/sync/items', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const items = await Item.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
res.json({ status: 'ok', items });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/sync/map-item', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const { itemId, foundryItemId, worldId } = req.body;
if (!requestMatchesWorld(campaign, worldId) || !itemId || !foundryItemId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const item = await Item.findOne({ _id: itemId, campaign: campaign._id });
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
const existing = await Item.findOne({ campaign: campaign._id, foundryItemId, _id: { $ne: item._id } });
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.item-already-synced' });
item.foundryItemId = String(foundryItemId).trim().slice(0, 120);
await item.save();
res.json({ status: 'ok', item });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
module.exports = router; module.exports = router;

View File

@@ -42,6 +42,31 @@ router.post('/create', async (req, res) => {
} }
}); });
router.post('/update', async (req, res) => {
try {
const { id, name, category, rarity, quantity, weight, properties, description } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const item = await Item.findById(id);
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(item.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
if (name !== undefined) item.name = String(name).trim();
if (category !== undefined) item.category = category;
if (rarity !== undefined) item.rarity = rarity;
if (quantity !== undefined && quantity !== '') item.quantity = Number(quantity);
if (weight !== undefined && weight !== '') item.weight = Number(weight);
if (properties !== undefined) item.properties = properties;
if (description !== undefined) item.description = description;
await item.save();
res.json({ status: 'ok', item });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/delete', async (req, res) => { router.post('/delete', async (req, res) => {
try { try {
const { id } = req.body; const { id } = req.body;

View File

@@ -1,30 +1,4 @@
function numberOr(value, fallback) { const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
const number = Number(value);
return Number.isFinite(number) ? number : fallback;
}
function asText(value) {
return typeof value === 'string' ? value : '';
}
function plainText(value) {
return asText(value)
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p\s*>/gi, '\n')
.replace(/<[^>]*>/g, ' ')
.replace(/&nbsp;/gi, ' ')
.replace(/&amp;/gi, '&')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
.replace(/\s+\n/g, '\n')
.trim();
}
function traitList(value) {
if (Array.isArray(value)) return value.map(asText).filter(Boolean);
if (typeof value === 'string') return [value];
return [];
}
function foundryActorToCharacter(foundryActor) { function foundryActorToCharacter(foundryActor) {
const system = foundryActor.system || {}; const system = foundryActor.system || {};
@@ -40,10 +14,10 @@ function foundryActorToCharacter(foundryActor) {
const savedDragonrollFields = foundryActor.flags?.['dragonroll-foundry'] || {}; const savedDragonrollFields = foundryActor.flags?.['dragonroll-foundry'] || {};
const savedDragonrollType = savedDragonrollFields.actorType; const savedDragonrollType = savedDragonrollFields.actorType;
const foundryProficiencies = [ const foundryProficiencies = [
...traitList(traits.languages?.value), ...stringList(traits.languages?.value),
...traitList(traits.armor?.value), ...stringList(traits.armor?.value),
...traitList(traits.weapon?.value), ...stringList(traits.weapon?.value),
...traitList(traits.tool?.value) ...stringList(traits.tool?.value)
].join(', '); ].join(', ');
return { return {

View File

@@ -0,0 +1,32 @@
// Small helpers shared by the Foundry -> Dragonroll document mappers
// (services/actor-foundry.js and services/item-foundry.js).
function numberOr(value, fallback) {
const number = Number(value);
return Number.isFinite(number) ? number : fallback;
}
function asText(value) {
return typeof value === 'string' ? value : '';
}
function plainText(value) {
return asText(value)
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p\s*>/gi, '\n')
.replace(/<[^>]*>/g, ' ')
.replace(/&nbsp;/gi, ' ')
.replace(/&amp;/gi, '&')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
.replace(/\s+\n/g, '\n')
.trim();
}
function stringList(value) {
if (Array.isArray(value)) return value.map(asText).filter(Boolean);
if (typeof value === 'string') return [value];
return [];
}
module.exports = { numberOr, asText, plainText, stringList };

View File

@@ -0,0 +1,108 @@
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
// Foundry item types that are gear, mapped to a Dragonroll Item category.
// `equipment` is resolved into armor / shield from its armor type.
const CATEGORY_BY_FOUNDRY_TYPE = {
weapon: 'weapon',
equipment: 'equipment',
consumable: 'consumable',
tool: 'tool',
container: 'adventuring-gear',
loot: 'treasure',
// Item types from older D&D 5e system releases.
ammo: 'weapon',
potion: 'consumable',
poison: 'consumable',
scroll: 'consumable',
trinket: 'magic-item',
backpack: 'adventuring-gear'
};
// Foundry item types that are not gear: they never become Dragonroll items.
const NON_GEAR_FOUNDRY_TYPES = new Set([
'spell', 'class', 'subclass', 'background', 'feat', 'race', 'species', 'status', 'spellbook', 'language'
]);
// Item categories the Dragonroll Item model accepts.
const CATEGORIES = ['weapon', 'armor', 'shield', 'adventuring-gear', 'magic-item', 'consumable', 'tool', 'treasure', 'other'];
const RARITY_BY_FOUNDRY_VALUE = {
common: 'common',
uncommon: 'uncommon',
rare: 'rare',
'very-rare': 'very-rare',
veryrare: 'very-rare',
'very rare': 'very-rare',
legendary: 'legendary',
artifact: 'artifact'
};
// Fallback labels for weapon properties when the Foundry client did not send the
// ones from its own CONFIG (see serializeFoundryItem in the module).
const WEAPON_PROPERTY_LABELS = {
amm: 'ammunition',
fin: 'finesse',
foc: 'focus',
hvy: 'heavy',
lrp: 'long range',
lod: 'loading',
nid: 'noisy',
rch: 'reach',
rel: 'reload',
ret: 'retractable',
slo: 'slow firing',
thr: 'thrown',
thv: 'thrown',
two: 'two-handed',
ver: 'versatile'
};
function foundryItemRarity(foundryItem) {
const rarity = asText(foundryItem.system?.rarity).toLowerCase().trim();
return RARITY_BY_FOUNDRY_VALUE[rarity] || 'common';
}
// Returns null for Foundry documents that are not gear so the sync can skip them.
function foundryItemCategory(foundryItem, rarity) {
const type = asText(foundryItem.type).toLowerCase().trim();
if (NON_GEAR_FOUNDRY_TYPES.has(type)) return null;
if (type === 'equipment') {
return asText(foundryItem.system?.armor?.type).toLowerCase() === 'shield' ? 'shield' : 'armor';
}
const category = CATEGORY_BY_FOUNDRY_TYPE[type];
if (CATEGORIES.includes(category)) return category;
// Systems the module does not know about still get a usable Dragonroll item.
return rarity === 'common' ? 'other' : 'magic-item';
}
function foundryItemProperties(foundryItem) {
const provided = stringList(foundryItem.dragonroll?.properties);
if (provided.length) return provided.join(', ');
const properties = stringList(foundryItem.system?.properties?.value ?? foundryItem.system?.properties);
return properties.map((property) => {
const key = property.toLowerCase();
return Object.hasOwn(WEAPON_PROPERTY_LABELS, key) ? WEAPON_PROPERTY_LABELS[key] : property;
}).join(', ');
}
function foundryItemToItemData(foundryItem) {
const system = foundryItem.system || {};
const name = asText(foundryItem.name).trim();
const rarity = foundryItemRarity(foundryItem);
const category = foundryItemCategory(foundryItem, rarity);
if (!name || !category) return null;
return {
name,
category,
rarity,
quantity: Math.max(1, Math.trunc(numberOr(system.quantity, 1))),
weight: Math.max(0, numberOr(system.weight?.value ?? system.weight, 0)),
properties: foundryItemProperties(foundryItem),
description: plainText(system.description?.value ?? system.description)
};
}
module.exports = { foundryItemToItemData };

View File

@@ -3,7 +3,7 @@
Foundry modules run in the game client, so the module cannot bind an HTTP port on the Foundry host. Foundry modules run in the game client, so the module cannot bind an HTTP port on the Foundry host.
This integration uses a small companion bridge process on that host: This integration uses a small companion bridge process on that host:
1. A linked GM client syncs character Actors directly with the Dragonroll campaign. 1. A linked GM client syncs character Actors and world Items directly with the Dragonroll campaign.
2. The module publishes the active world's actor and item snapshot to the optional bridge. 2. The module publishes the active world's actor and item snapshot to the optional bridge.
3. The bridge serves authenticated HTTP read endpoints that Dragonroll proxies under `/api/foundry/*`. 3. The bridge serves authenticated HTTP read endpoints that Dragonroll proxies under `/api/foundry/*`.
@@ -45,7 +45,7 @@ The campaign settings show the linked world's title and system. A Foundry world
only one campaign at a time. The pairing endpoint accepts cross-origin requests from the Foundry only one campaign at a time. The pairing endpoint accepts cross-origin requests from the Foundry
client and uses the one-time code instead of a Dragonroll login token. client and uses the one-time code instead of a Dragonroll login token.
## Character synchronization ## Character and item synchronization
After linking, the GM client imports Foundry character, NPC, and creature Actors into the campaign. After linking, the GM client imports Foundry character, NPC, and creature Actors into the campaign.
Creates, updates, and deletes sync in either direction; Dragonroll changes are applied in Foundry Creates, updates, and deletes sync in either direction; Dragonroll changes are applied in Foundry
@@ -53,6 +53,44 @@ within about five seconds. The module currently creates Dragonroll characters in
worlds. After updating an already-linked world to a version with character sync, create a fresh worlds. After updating an already-linked world to a version with character sync, create a fresh
pairing code and enter it in Foundry once to issue the sync token. pairing code and enter it in Foundry once to issue the sync token.
### Items
The campaign's Item list is synchronized with the world's gear, both ways:
- 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
that character's snapshot instead.
- Gear is deduplicated by name: the same sword in the world directory and in three characters'
inventories becomes one Dragonroll item. Names Dragonroll renames away from are remembered on the
item (`foundryNames`), so Foundry's copies keep folding into it rather than coming back as a
duplicate. Spells, classes, subclasses, backgrounds, feats and species are not gear and are not
imported.
- 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
directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry
document.
- A full snapshot keeps Dragonroll edits on reconnect; live Foundry edits overwrite. Item removal is
pruned only by a full snapshot, so a live item push never deletes anything. Deleting a synced item in
Dragonroll removes its Foundry world copy on the next reconcile. Items that live only in an actor's
inventory are owned by that actor's snapshot: editing such an item in Dragonroll does not rewrite the
actor's copy.
The module calls these Dragonroll routes with the campaign sync token (no Dragonroll login):
| Route | Use |
|---|---|
| `POST /api/foundry/sync/snapshot` | Actors and world items upsert; `fullSync` also prunes |
| `POST /api/foundry/sync/item-snapshot` | Live world item edits, upsert only |
| `POST /api/foundry/sync/item-delete` | A world item was deleted |
| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry |
| `GET /api/foundry/sync/items` | Items to apply back in Foundry |
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
| `POST /api/foundry/sync/delete` | An actor was deleted |
Foundry documents keep the Dragonroll id in the `dragonroll-foundry.actorId` / `dragonroll-foundry.itemId`
flag, and world items are marked with `dragonroll-foundry.syncMutation` while Dragonroll writes them so
the write is not echoed back.
## 2. Run the bridge on the Foundry host ## 2. Run the bridge on the Foundry host
The bridge uses only Node.js built-in modules and requires Node 18 or newer. Set separate random The bridge uses only Node.js built-in modules and requires Node 18 or newer. Set separate random

View File

@@ -20,6 +20,11 @@ let characterSyncRunning = false;
let actorSyncErrorLogged = false; let actorSyncErrorLogged = false;
const syncingActorIds = new Set(); const syncingActorIds = new Set();
const queuedActorChanges = new Map(); const queuedActorChanges = new Map();
let itemSyncTimeout;
let itemSyncRunning = false;
let itemSyncErrorLogged = false;
const syncingItemIds = new Set();
const queuedItemChanges = new Map();
function getCollectionContents(collection, collectionName) { function getCollectionContents(collection, collectionName) {
if (!collection) { if (!collection) {
@@ -240,6 +245,7 @@ async function completeDragonrollCampaignLink(code, options = {}) {
} }
scheduleSnapshotSync(0); scheduleSnapshotSync(0);
setTimeout(initializeCharacterSync, 0); setTimeout(initializeCharacterSync, 0);
setTimeout(reconcileDragonrollItems, 2000);
ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign."); ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign.");
} catch (error) { } catch (error) {
console.error(`${MODULE_ID} | Could not complete the campaign link.`, error); console.error(`${MODULE_ID} | Could not complete the campaign link.`, error);
@@ -349,6 +355,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 actor copies keeps a single Item per piece of gear.
items: getWorldItemSnapshots(),
fullSync, fullSync,
}, token); }, token);
@@ -358,6 +367,7 @@ async function pushFoundryActors(actors, fullSync = false) {
await setDragonrollActorId(actor, mapping.actorId); await setDragonrollActorId(actor, mapping.actorId);
} }
} }
await rememberItemMappings(result.items);
actorSyncErrorLogged = false; actorSyncErrorLogged = false;
} }
@@ -378,7 +388,6 @@ function queueActorChange(kind, actor) {
clearTimeout(actorSyncTimeout); clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 400); actorSyncTimeout = setTimeout(flushActorChanges, 400);
} }
async function flushActorChanges() { async function flushActorChanges() {
const changes = [...queuedActorChanges.values()]; const changes = [...queuedActorChanges.values()];
queuedActorChanges.clear(); queuedActorChanges.clear();
@@ -396,6 +405,269 @@ async function flushActorChanges() {
} }
} }
// --- World item sync -------------------------------------------------------
// Items embedded in an actor travel with that actor's snapshot; the items below
// handle the world-level item directory (game.items) in both directions.
function itemPropertyLabels(item) {
const values = item.system?.properties?.value;
if (!Array.isArray(values) || !values.length || game.system?.id !== "dnd5e") return [];
const propertyConfigs = [
CONFIG.DND5E?.weaponProperties,
CONFIG.DND5E?.armorProperties,
CONFIG.DND5E?.toolProperties,
CONFIG.DND5E?.consumableProperties,
];
return values
.map((key) => {
for (const config of propertyConfigs) {
const label = config?.[key]?.label;
if (label) return String(label).toLowerCase();
}
return typeof key === "string" ? key : "";
})
.filter(Boolean);
}
function serializeFoundryItem(item) {
const data = toPlainData(item);
if (!data) return null;
if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) {
data.img = new URL(data.img, window.location.origin).toString();
}
// Dragonroll shows plain property text; send Foundry's own labels when present
// so keys such as "ver" do not end up in its Item list.
const properties = itemPropertyLabels(item);
if (properties.length) data.dragonroll = { properties };
return data;
}
function getWorldItemSnapshots() {
return (game.items?.contents || []).map(serializeFoundryItem).filter(Boolean);
}
function dragonrollItemIdOf(item) {
return item.getFlag?.(MODULE_ID, "itemId") || item.flags?.[MODULE_ID]?.itemId || "";
}
async function withItemSyncSuppressed(item, callback) {
if (!item?.id) return callback();
syncingItemIds.add(item.id);
try {
return await callback();
} finally {
syncingItemIds.delete(item.id);
}
}
async function setDragonrollItemId(item, itemId) {
if (!item || !itemId) return;
await withItemSyncSuppressed(item, () => item.update({
[`flags.${MODULE_ID}.itemId`]: String(itemId),
[`flags.${MODULE_ID}.syncMutation`]: false,
}));
}
async function rememberItemMappings(mappings) {
for (const mapping of mappings || []) {
const item = game.items?.get(mapping.foundryItemId);
if (item && String(dragonrollItemIdOf(item)) !== String(mapping.itemId)) {
await setDragonrollItemId(item, mapping.itemId);
}
}
}
function reportItemSyncError(error) {
if (itemSyncErrorLogged) return;
itemSyncErrorLogged = true;
console.warn(`${MODULE_ID} | Item sync failed and will retry.`, error);
}
// Item pushes are upserts only: the full world snapshot sent with the actors
// owns pruning, because it is the only one that sees every embedded copy.
async function pushFoundryItems(items) {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || !items.length) return;
const result = await postDragonroll("foundry/sync/item-snapshot", {
worldId: game.world.id,
items: items.map(serializeFoundryItem).filter(Boolean),
}, token);
await rememberItemMappings(result.items);
itemSyncErrorLogged = false;
}
async function deleteDragonrollItem(foundryItemId) {
const token = getSyncToken();
if (!token || !game.world || !foundryItemId) return;
await postDragonroll("foundry/sync/item-delete", {
worldId: game.world.id,
foundryItemId,
}, token);
}
function queueFoundryItemChange(kind, item) {
if (!item || !game.user?.isGM || !getSyncToken()) return;
if (syncingItemIds.has(item.id) || item.flags?.[MODULE_ID]?.syncMutation) return;
queuedItemChanges.set(item.id, { kind, item });
clearTimeout(itemSyncTimeout);
itemSyncTimeout = setTimeout(flushItemChanges, 400);
}
async function flushItemChanges() {
const changes = [...queuedItemChanges.values()];
queuedItemChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete");
const changed = changes.filter((change) => change.kind !== "delete");
try {
for (const change of deleted) await deleteDragonrollItem(change.item.id);
if (changed.length) await pushFoundryItems(changed.map((change) => change.item));
} catch (error) {
reportItemSyncError(error);
for (const change of changes) queuedItemChanges.set(change.item.id, change);
clearTimeout(itemSyncTimeout);
itemSyncTimeout = setTimeout(flushItemChanges, 5000);
}
}
const CATEGORY_TO_FOUNDRY_ITEM_TYPE = {
weapon: "weapon",
armor: "equipment",
shield: "equipment",
consumable: "consumable",
tool: "tool",
"adventuring-gear": "loot",
"magic-item": "loot",
treasure: "loot",
other: "loot",
};
const RARITY_TO_FOUNDRY_VALUE = {
common: "common",
uncommon: "uncommon",
rare: "rare",
"very-rare": "veryRare",
legendary: "legendary",
artifact: "artifact",
};
function makeFoundryItemData(entry) {
const type = CATEGORY_TO_FOUNDRY_ITEM_TYPE[entry.category] || "loot";
const data = {
name: String(entry.name || "").trim(),
type,
system: {
quantity: Number(entry.quantity) || 1,
weight: Number(entry.weight) || 0,
rarity: RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common",
description: { value: entry.description || "" },
},
flags: { [MODULE_ID]: { itemId: String(entry._id), syncMutation: true } },
};
if (type === "equipment") data.system.armor = { type: entry.category === "shield" ? "shield" : "medium" };
return data;
}
function foundryItemUpdateData(entry) {
return {
name: String(entry.name || "").trim(),
"system.quantity": Number(entry.quantity) || 1,
"system.weight": Number(entry.weight) || 0,
"system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common",
"system.description.value": entry.description || "",
};
}
async function applyDragonrollItem(item, entry) {
const updates = foundryItemUpdateData(entry);
const changed = Object.entries(updates).some(([key, value]) => documentValue(item, key) !== value);
await withItemSyncSuppressed(item, async () => {
if (changed) await item.update(updates);
if (dragonrollItemIdOf(item) !== String(entry._id)) {
await item.update({ [`flags.${MODULE_ID}.itemId`]: String(entry._id) });
}
});
}
async function mapDragonrollItem(itemId, foundryItemId) {
const token = getSyncToken();
return postDragonroll("foundry/sync/map-item", {
worldId: game.world.id,
itemId: String(itemId),
foundryItemId: String(foundryItemId),
}, token);
}
async function createFoundryWorldItem(entry) {
const data = makeFoundryItemData(entry);
if (!data.name) return;
const item = await Item.create(data);
if (!item) return;
await withItemSyncSuppressed(item, async () => {
await item.update({ [`flags.${MODULE_ID}.syncMutation`]: false });
});
await mapDragonrollItem(entry._id, item.id);
}
async function reconcileDragonrollItems() {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || itemSyncRunning) return;
itemSyncRunning = true;
try {
if (game.system.id !== "dnd5e") {
throw new Error("Item sync currently requires the D&D 5e Foundry system.");
}
const result = await getDragonroll("foundry/sync/items", token);
const remoteItems = result.items || [];
const remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry]));
const localByRemoteId = new Map(game.items.contents
.map((item) => [String(dragonrollItemIdOf(item)), item])
.filter(([itemId]) => itemId));
const retainedFoundryIds = new Set();
for (const entry of remoteItems) {
let item = entry.foundryItemId ? game.items.get(entry.foundryItemId) : null;
if (!item) item = localByRemoteId.get(String(entry._id));
if (item) {
retainedFoundryIds.add(item.id);
await applyDragonrollItem(item, entry);
if (!entry.foundryItemId) await mapDragonrollItem(entry._id, item.id);
} else if (entry.foundryItemId) {
// Imported gear that only exists inside an actor's inventory: its actor
// snapshot owns it, so cloning it into the world would duplicate it.
continue;
} else {
// A Dragonroll item named like an unmapped Foundry item maps to that
// document instead of adding a second copy of the same gear.
const sameName = game.items.contents.find((candidate) => candidate.name === String(entry.name).trim()
&& !dragonrollItemIdOf(candidate));
if (sameName) {
retainedFoundryIds.add(sameName.id);
await mapDragonrollItem(entry._id, sameName.id);
} else {
await createFoundryWorldItem(entry);
}
}
}
for (const item of game.items.contents) {
const itemId = dragonrollItemIdOf(item);
if (!itemId || retainedFoundryIds.has(item.id) || remoteById.has(String(itemId))) continue;
await withItemSyncSuppressed(item, () => item.delete());
}
itemSyncErrorLogged = false;
} catch (error) {
reportItemSyncError(error);
} finally {
itemSyncRunning = false;
}
}
function getDragonrollImageUrl(image) { function getDragonrollImageUrl(image) {
if (!image) return ""; if (!image) return "";
if (/^(https?:|data:|\/\/)/i.test(image)) return image; if (/^(https?:|data:|\/\/)/i.test(image)) return image;
@@ -715,6 +987,10 @@ Hooks.once("ready", () => {
setInterval(publishHeartbeat, 60000); setInterval(publishHeartbeat, 60000);
setTimeout(initializeCharacterSync, 1000); setTimeout(initializeCharacterSync, 1000);
setInterval(reconcileDragonrollCharacters, 5000); setInterval(reconcileDragonrollCharacters, 5000);
// Items reconcile after the character snapshot has landed so Dragonroll has
// already seen the world directory when it starts sending its own items back.
setTimeout(reconcileDragonrollItems, 2000);
setInterval(reconcileDragonrollItems, 5000);
for (const event of [ for (const event of [
"createActor", "updateActor", "deleteActor", "createActor", "updateActor", "deleteActor",
@@ -722,10 +998,21 @@ Hooks.once("ready", () => {
]) { ]) {
Hooks.on(event, (document) => { Hooks.on(event, (document) => {
scheduleSnapshotSync(); scheduleSnapshotSync();
const actor = document.documentName === "Actor" ? document : document.parent; const isDelete = event.startsWith("delete");
if (actor?.documentName === "Actor") {
queueFoundryActorChange(event.startsWith("delete") ? "delete" : "upsert", actor); if (document.documentName === "Actor") {
queueFoundryActorChange(isDelete ? "delete" : "upsert", document);
return;
} }
if (document.documentName !== "Item") return;
// Items embedded in an actor travel with that actor's snapshot: adding or
// removing one only changes the actor, never deletes it.
if (document.parent?.documentName === "Actor") {
queueFoundryActorChange("upsert", document.parent);
return;
}
queueFoundryItemChange(isDelete ? "delete" : "upsert", document);
}); });
} }
}); });

View File

@@ -25,7 +25,7 @@ const isDragOverSidebar = ref(false);
const expandedFolderIds = ref([]); const expandedFolderIds = ref([]);
const expandedEntryIds = ref([]); const expandedEntryIds = ref([]);
const nestedNoteListRef = ref(null); const nestedNoteListRef = ref(null);
let actorRefreshInterval; let entryRefreshInterval;
async function handleSidebarDrop(event) { async function handleSidebarDrop(event) {
if (activeSection.value !== 'notes') return; if (activeSection.value !== 'notes') return;
@@ -171,17 +171,17 @@ async function fetchCampaignEntries(entityType = activeSection.value, silent = f
if (!silent) entriesError.value = response.data.msg ?? t('campaigns.errors.load'); if (!silent) entriesError.value = response.data.msg ?? t('campaigns.errors.load');
return; return;
} }
if (entityType === 'actors') {
const previousById = new Map(actors.value.map((actor) => [actor._id, actor])); const kind = entityType === 'actors' ? 'actor' : 'item';
actors.value = response.data.actors; const list = entityType === 'actors' ? actors : items;
for (const actor of actors.value) { const previousById = new Map(list.value.map((entry) => [entry._id, entry]));
const previous = previousById.get(actor._id); list.value = response.data[entityType];
if (previous && JSON.stringify(previous) !== JSON.stringify(actor)) { // Tell open windows about Foundry changes landing behind them.
emitter.emit('campaign-entry-updated', { entityType: 'actor', entry: actor }); for (const entry of list.value) {
} const previous = previousById.get(entry._id);
if (previous && JSON.stringify(previous) !== JSON.stringify(entry)) {
emitter.emit('campaign-entry-updated', { entityType: kind, entry });
} }
} else {
items.value = response.data.items;
} }
} catch (error) { } catch (error) {
if (!silent) entriesError.value = t('campaigns.errors.load'); if (!silent) entriesError.value = t('campaigns.errors.load');
@@ -213,9 +213,25 @@ function itemSummary(item) {
return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`; return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`;
} }
function editItem(entry) {
if (!campaignId.value) return;
CreateWindow('create_campaign_entry', { entityType: 'item', campaign: campaignId.value, entry });
}
function showEntryMenu(entry, entityType) { function showEntryMenu(entry, entityType) {
const collection = entityType === 'actor' ? 'actor' : 'item'; const collection = entityType === 'actor' ? 'actor' : 'item';
ShowContextMenu([{ const menuItems = [];
// Characters are edited in their sheet; items get the entry window in edit mode.
if (entityType !== 'actor') {
menuItems.push({
name: t('campaigns.actions.edit'),
icon: '/icons/iconoir/regular/edit.svg',
action: () => { HideContextMenu(); editItem(entry); }
});
}
menuItems.push({
name: t('campaigns.actions.delete'), name: t('campaigns.actions.delete'),
icon: '/icons/iconoir/regular/trash.svg', icon: '/icons/iconoir/regular/trash.svg',
action: async () => { action: async () => {
@@ -227,7 +243,8 @@ function showEntryMenu(entry, entityType) {
} }
} catch (error) {} finally { HideContextMenu(); } } catch (error) {} finally { HideContextMenu(); }
} }
}]); });
ShowContextMenu(menuItems);
} }
function toggleEntryDetails(entryId) { function toggleEntryDetails(entryId) {
@@ -289,13 +306,16 @@ onMounted(() => {
if (campaignId.value) { if (campaignId.value) {
fetchCampaignNotes(); fetchCampaignNotes();
} }
actorRefreshInterval = setInterval(() => { entryRefreshInterval = setInterval(() => {
if (activeSection.value === 'actors' && campaignId.value) fetchCampaignEntries('actors', true); // Synced Foundry entries land in the background for both lists.
if ((activeSection.value === 'actors' || activeSection.value === 'items') && campaignId.value) {
fetchCampaignEntries(activeSection.value, true);
}
}, 5000); }, 5000);
}); });
onBeforeUnmount(() => { onBeforeUnmount(() => {
clearInterval(actorRefreshInterval); clearInterval(entryRefreshInterval);
emitter.off('note-created', handleNoteCreated); emitter.off('note-created', handleNoteCreated);
emitter.off('note-renamed', handleNoteRenamed); emitter.off('note-renamed', handleNoteRenamed);
emitter.off('delete-note', handleNoteDeleted); emitter.off('delete-note', handleNoteDeleted);
@@ -412,7 +432,10 @@ onBeforeUnmount(() => {
<div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div> <div v-else-if="entriesError" class="sidebar-state error">{{ entriesError }}</div>
<div v-else-if="items.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div> <div v-else-if="items.length === 0" class="sidebar-state">{{ t('campaigns.states.empty-items') }}</div>
<div v-for="item in items" :key="item._id" class="entity-entry" role="button" tabindex="0" :aria-expanded="expandedEntryIds.includes(item._id)" @click="toggleEntryDetails(item._id)" @keydown.enter="toggleEntryDetails(item._id)" @keydown.space.prevent="toggleEntryDetails(item._id)" @contextmenu.prevent="showEntryMenu(item, 'item')"> <div v-for="item in items" :key="item._id" class="entity-entry" role="button" tabindex="0" :aria-expanded="expandedEntryIds.includes(item._id)" @click="toggleEntryDetails(item._id)" @keydown.enter="toggleEntryDetails(item._id)" @keydown.space.prevent="toggleEntryDetails(item._id)" @contextmenu.prevent="showEntryMenu(item, 'item')">
<span class="entity-entry-name">{{ item.name }}</span> <span class="entity-entry-name-row">
<span class="entity-entry-name">{{ item.name }}</span>
<span v-if="item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span>
</span>
<span class="entity-entry-meta">{{ itemSummary(item) }}</span> <span class="entity-entry-meta">{{ itemSummary(item) }}</span>
<template v-if="expandedEntryIds.includes(item._id)"> <template v-if="expandedEntryIds.includes(item._id)">
<span v-if="item.weight !== undefined" class="entity-entry-description">{{ item.weight }} lb</span> <span v-if="item.weight !== undefined" class="entity-entry-description">{{ item.weight }} lb</span>
@@ -567,7 +590,14 @@ onBeforeUnmount(() => {
} }
.entity-entry:hover { border-color: var(--color-border); background: var(--color-background-soft); } .entity-entry:hover { border-color: var(--color-border); background: var(--color-background-soft); }
.entity-entry:focus-visible { outline: 1px solid var(--color-link); } .entity-entry:focus-visible { outline: 1px solid var(--color-link); }
.entity-entry-name-row { display: flex; align-items: baseline; gap: 6px; }
.entity-entry-name { font-weight: bold; } .entity-entry-name { font-weight: bold; }
.entity-entry-sync {
font-size: 10px;
letter-spacing: 0.04em;
text-transform: uppercase;
opacity: 0.6;
}
.entity-entry-meta, .entity-entry-description { font-size: 12px; opacity: 0.72; } .entity-entry-meta, .entity-entry-description { font-size: 12px; opacity: 0.72; }
.entity-entry-description { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; } .entity-entry-description { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }

View File

@@ -11,13 +11,27 @@ const id = data.id;
const handle = ref(null); const handle = ref(null);
const wrapper = ref(null); const wrapper = ref(null);
const saving = ref(false); const saving = ref(false);
const form = ref({ // The window edits items when the sidebar passes one in; actors have their sheet.
name: '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '', const editing = data.entry || null;
category: 'adventuring-gear', rarity: 'common', quantity: 1, weight: '', properties: '', description: ''
});
const isActor = data.entityType === 'actor'; const isActor = data.entityType === 'actor';
const endpoint = isActor ? '/actor/create' : '/item/create'; const endpoint = isActor ? '/actor/create' : (editing ? '/item/update' : '/item/create');
function initialForm() {
if (!editing) {
return {
name: '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '',
category: 'adventuring-gear', rarity: 'common', quantity: 1, weight: '', properties: '', description: ''
};
}
return {
name: editing.name ?? '', type: 'character', species: '', className: '', level: '', background: '', challengeRating: '',
category: editing.category ?? 'adventuring-gear', rarity: editing.rarity ?? 'common',
quantity: editing.quantity ?? 1, weight: editing.weight ?? '', properties: editing.properties ?? '',
description: editing.description ?? ''
};
}
const form = ref(initialForm());
onMounted(() => { onMounted(() => {
SetupHandle(id, handle); SetupHandle(id, handle);
@@ -31,7 +45,9 @@ async function saveEntry() {
if (!form.value.name.trim() || saving.value) return; if (!form.value.name.trim() || saving.value) return;
saving.value = true; saving.value = true;
try { try {
const payload = { name: form.value.name.trim(), campaign: data.campaign }; const payload = isActor
? { name: form.value.name.trim(), 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', 'quantity', 'weight', 'properties', 'description']) {
payload[field] = form.value[field]; payload[field] = form.value[field];
@@ -39,7 +55,7 @@ async function saveEntry() {
} }
const response = await Server().post(endpoint, payload); const response = await Server().post(endpoint, payload);
if (response.data.status === 'ok') { if (response.data.status === 'ok') {
emitter.emit('campaign-entry-created', { entityType: data.entityType, entry: response.data[isActor ? 'actor' : 'item'] }); emitter.emit(editing ? 'campaign-entry-updated' : 'campaign-entry-created', { entityType: data.entityType, entry: response.data[isActor ? 'actor' : 'item'] });
ClearWindow({ id }); ClearWindow({ id });
} }
} catch (error) { } catch (error) {
@@ -54,7 +70,8 @@ async function saveEntry() {
<div class="window-wrapper" :id="'window-wrapper-' + id" ref="wrapper"> <div class="window-wrapper" :id="'window-wrapper-' + id" ref="wrapper">
<WindowHandle :window="id" ref="handle" /> <WindowHandle :window="id" ref="handle" />
<div class="body"> <div class="body">
<h3>{{ $t(isActor ? 'campaigns.actor.new' : 'campaigns.item.new') }}</h3> <h3>{{ $t(editing ? 'campaigns.item.edit' : (isActor ? 'campaigns.actor.new' : 'campaigns.item.new')) }}</h3>
<p v-if="!isActor && editing?.foundryItemId" class="sync-note">{{ $t('campaigns.item.foundry-sync-note') }}</p>
<form @submit.prevent="saveEntry"> <form @submit.prevent="saveEntry">
<label class="form-field"> <label class="form-field">
<span>{{ $t('campaigns.fields.name') }}</span> <span>{{ $t('campaigns.fields.name') }}</span>
@@ -109,7 +126,7 @@ async function saveEntry() {
</label> </label>
<div class="form-actions"> <div class="form-actions">
<button class="btn-primary sound-click" type="submit" :disabled="saving"> <button class="btn-primary sound-click" type="submit" :disabled="saving">
{{ saving ? $t('campaigns.actions.saving') : $t('campaigns.actions.submit') }} {{ saving ? $t('campaigns.actions.saving') : $t(editing ? 'campaigns.actions.save' : 'campaigns.actions.submit') }}
</button> </button>
</div> </div>
</form> </form>
@@ -121,6 +138,7 @@ async function saveEntry() {
.window-wrapper { display: flex; align-items: center; flex-direction: column; } .window-wrapper { display: flex; align-items: center; flex-direction: column; }
.body { width: 100%; padding: 10px 18px 16px; overflow-y: auto; } .body { width: 100%; padding: 10px 18px 16px; overflow-y: auto; }
h3 { margin: 0 0 12px; font-family: MrEavesRemake; } h3 { margin: 0 0 12px; font-family: MrEavesRemake; }
.sync-note { margin: -8px 0 12px; font-size: 12px; opacity: 0.72; }
form { display: flex; flex-direction: column; gap: 10px; } form { display: flex; flex-direction: column; gap: 10px; }
.form-field { min-width: 0; display: flex; flex-direction: column; gap: 4px; font-size: 13px; } .form-field { min-width: 0; display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }

View File

@@ -27,10 +27,11 @@
} }
}, },
"sidebar-label": "Campanya", "sidebar-label": "Campanya",
"synced": "Sincronitzat",
"sections": { "notes": "Notes", "actors": "Actors i personatges", "items": "Objectes" }, "sections": { "notes": "Notes", "actors": "Actors i personatges", "items": "Objectes" },
"actions": { "actions": {
"new-note": "Nota nova", "new-folder": "Carpeta nova", "refresh": "Actualitza", "new-note": "Nota nova", "new-folder": "Carpeta nova", "refresh": "Actualitza",
"create": "Crea {section}", "submit": "Crea", "delete": "Suprimeix", "saving": "Desant...", "create": "Crea {section}", "submit": "Crea", "edit": "Edita", "save": "Desa", "delete": "Suprimeix", "saving": "Desant...",
"collapse-sidebar": "Redueix la barra lateral", "expand-sidebar": "Expandeix la barra lateral" "collapse-sidebar": "Redueix la barra lateral", "expand-sidebar": "Expandeix la barra lateral"
}, },
"states": { "states": {
@@ -47,7 +48,8 @@
"types": { "character": "Personatge", "npc": "PNJ", "creature": "Criatura" } "types": { "character": "Personatge", "npc": "PNJ", "creature": "Criatura" }
}, },
"item": { "item": {
"new": "Objecte nou", "category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat", "new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.",
"category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat",
"quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil", "quantity-short": "Quant.", "weight": "Pes (lb)", "properties": "Propietats", "properties-placeholder": "Per exemple, versàtil, subtil",
"categories": { "categories": {
"weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura", "weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura",

View File

@@ -1,6 +1,8 @@
{ {
"errors": { "errors": {
"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.",
"item-already-synced": "Un altre objecte d'aquesta campanya ja està sincronitzat amb aquell objecte del Foundry."
} }
} }

View File

@@ -31,10 +31,11 @@
} }
}, },
"sidebar-label": "Campaign", "sidebar-label": "Campaign",
"synced": "Synced",
"sections": { "notes": "Notes", "actors": "Actors & Characters", "items": "Items" }, "sections": { "notes": "Notes", "actors": "Actors & Characters", "items": "Items" },
"actions": { "actions": {
"new-note": "New note", "new-folder": "New folder", "refresh": "Refresh", "new-note": "New note", "new-folder": "New folder", "refresh": "Refresh",
"create": "Create {section}", "submit": "Create", "delete": "Delete", "saving": "Saving...", "create": "Create {section}", "submit": "Create", "edit": "Edit", "save": "Save", "delete": "Delete", "saving": "Saving...",
"collapse-sidebar": "Collapse sidebar", "expand-sidebar": "Expand sidebar" "collapse-sidebar": "Collapse sidebar", "expand-sidebar": "Expand sidebar"
}, },
"states": { "states": {
@@ -51,7 +52,8 @@
"types": { "character": "Character", "npc": "NPC", "creature": "Creature" } "types": { "character": "Character", "npc": "NPC", "creature": "Creature" }
}, },
"item": { "item": {
"new": "New item", "category": "Category", "rarity": "Rarity", "quantity": "Quantity", "new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.",
"category": "Category", "rarity": "Rarity", "quantity": "Quantity",
"quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse", "quantity-short": "Qty", "weight": "Weight (lb)", "properties": "Properties", "properties-placeholder": "For example, versatile, finesse",
"categories": { "categories": {
"weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear", "weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear",

View File

@@ -1,6 +1,8 @@
{ {
"errors": { "errors": {
"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.",
"item-already-synced": "Another item in this campaign is already synced with that Foundry item."
} }
} }

View File

@@ -27,10 +27,11 @@
} }
}, },
"sidebar-label": "Campaña", "sidebar-label": "Campaña",
"synced": "Sincronizado",
"sections": { "notes": "Notas", "actors": "Actores y personajes", "items": "Objetos" }, "sections": { "notes": "Notas", "actors": "Actores y personajes", "items": "Objetos" },
"actions": { "actions": {
"new-note": "Nueva nota", "new-folder": "Nueva carpeta", "refresh": "Actualizar", "new-note": "Nueva nota", "new-folder": "Nueva carpeta", "refresh": "Actualizar",
"create": "Crear {section}", "submit": "Crear", "delete": "Eliminar", "saving": "Guardando...", "create": "Crear {section}", "submit": "Crear", "edit": "Editar", "save": "Guardar", "delete": "Eliminar", "saving": "Guardando...",
"collapse-sidebar": "Contraer barra lateral", "expand-sidebar": "Expandir barra lateral" "collapse-sidebar": "Contraer barra lateral", "expand-sidebar": "Expandir barra lateral"
}, },
"states": { "states": {
@@ -47,7 +48,8 @@
"types": { "character": "Personaje", "npc": "PNJ", "creature": "Criatura" } "types": { "character": "Personaje", "npc": "PNJ", "creature": "Criatura" }
}, },
"item": { "item": {
"new": "Nuevo objeto", "category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad", "new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.",
"category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad",
"quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil", "quantity-short": "Cant.", "weight": "Peso (lb)", "properties": "Propiedades", "properties-placeholder": "Por ejemplo, versátil, sutil",
"categories": { "categories": {
"weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura", "weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura",

View File

@@ -1,6 +1,8 @@
{ {
"errors": { "errors": {
"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.",
"item-already-synced": "Otro objeto de esta campaña ya está sincronizado con ese objeto de Foundry."
} }
} }