Merge branch 'master' into ai/issue-90
All checks were successful
Test / test (push) Successful in 2s

This commit is contained in:
2026-10-15 22:02:01 +00:00
11 changed files with 851 additions and 150 deletions

View File

@@ -9,6 +9,7 @@ const Item = require('../models/Item');
const Folder = require('../models/Folder');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
const { joinFoundryAssetUrl } = require('../services/foundry-icons');
// Upper bound for the Foundry names remembered per synced item (see Item model).
const MAX_FOUNDRY_NAMES = 20;
@@ -41,10 +42,33 @@ function requestMatchesWorld(campaign, worldId) {
return typeof worldId === 'string' && worldId === campaign.foundryWorldId;
}
// Foundry serves its data directory from the world's own address, which is the one the
// campaign keeps under `settings.integrations.foundryUrl` — the icon window already loads
// the world's icons through it. The module sends the images it publishes as absolute URLs;
// the bridge's snapshot and older modules carry Foundry's relative paths, and a sheet
// reading one of those against Dragonroll's upload folder finds nothing, which is how the
// icons stopped loading (Syndria98/dragonroll#89). An absolute URL travels as it is, and so
// does a path when the campaign has no world address to read it against.
function worldAssetUrl(image, worldUrl) {
const value = String(image ?? '').trim();
if (!value || /^(https?:|data:|\/\/)/i.test(value)) return value;
return joinFoundryAssetUrl(worldUrl, value) || value;
}
// The images a world document arrives with, read against its world before they land.
function resolveWorldAssets(fields, campaign) {
const worldUrl = campaign?.settings?.integrations?.foundryUrl;
if (typeof fields.image === 'string') fields.image = worldAssetUrl(fields.image, worldUrl);
if (Array.isArray(fields.inventory)) {
for (const entry of fields.inventory) entry.icon = worldAssetUrl(entry.icon, worldUrl);
}
}
async function saveFoundryActor(campaign, source, fullSync = false) {
const foundryActorId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryActorToCharacter(source || {});
if (!foundryActorId || !fields.name) return null;
resolveWorldAssets(fields, campaign);
let actor = await Actor.findOne({ campaign: campaign._id, foundryActorId });
const dragonrollActorId = source?.flags?.['dragonroll-foundry']?.actorId;
@@ -85,6 +109,7 @@ async function saveFoundryItem(campaign, source, fullSync = false, folders = nul
const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryItemToItemData(source || {});
if (!foundryItemId || !fields) return null;
resolveWorldAssets(fields, campaign);
let item = await Item.findOne({ campaign: campaign._id, foundryItemId });
const dragonrollItemId = source?.flags?.['dragonroll-foundry']?.itemId;

View File

@@ -1,4 +1,5 @@
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
const { isFoundryGearType } = require('./item-foundry');
// D&D 5e keeps an actor's background, species, class and subclass as a reference to an
// embedded item: `system.details.background` and friends hold that item's id, and the
@@ -169,8 +170,11 @@ function foundryActorToCharacter(foundryActor) {
armorClass: numberOr(attributes.ac?.value ?? attributes.ac, 10),
speed: numberOr(movement.walk ?? movement.value, 30),
proficiencies: foundryProficiencies || asText(savedDragonrollFields.proficiencies),
// What the character carries: gear, and gear only (Syndria98/dragonroll#89). A feat
// is a trait — its tab shows it — and a race is the species; standing them in the
// inventory next to the longswords is how traits and items got mixed up.
inventory: items
.filter((item) => !['class', 'subclass', 'background', 'spell'].includes(item.type))
.filter((item) => isFoundryGearType(item.type))
.map((item) => ({
name: asText(item.name).trim(),
quantity: numberOr(item.system?.quantity, 1),

View File

@@ -23,6 +23,14 @@ const NON_GEAR_FOUNDRY_TYPES = new Set([
'spell', 'class', 'subclass', 'background', 'feat', 'race', 'species', 'status', 'spellbook', 'language'
]);
// Whether a Foundry document of this type is gear: something a character carries. Traits,
// species, spells and the rest are documents of the world that mean something else on a
// Dragonroll sheet — a feat is a trait and a race is a species — so they stand in the
// character's own fields, never in its inventory (Syndria98/dragonroll#89).
function isFoundryGearType(type) {
return !NON_GEAR_FOUNDRY_TYPES.has(asText(type).toLowerCase().trim());
}
// Item categories the Dragonroll Item model accepts.
const CATEGORIES = ['weapon', 'armor', 'shield', 'adventuring-gear', 'magic-item', 'consumable', 'tool', 'treasure', 'other'];
@@ -107,4 +115,4 @@ function foundryItemToItemData(foundryItem) {
};
}
module.exports = { foundryItemToItemData };
module.exports = { foundryItemToItemData, isFoundryGearType };

View File

@@ -523,9 +523,16 @@ function isSupportedCharacterActor(actor) {
return ["character", "npc", "creature"].includes(savedType || actor.type);
}
// Embedded documents the world owns outright (Syndria98/dragonroll#89): a feat is a trait
// and a race is a species — they reach the campaign through its traits and species fields,
// never through its inventory. Dragonroll must neither mark them as its own nor delete one
// when it writes the character, and an older campaign still holding such a row in its
// inventory must be let to write it out of the campaign without the document going with it.
const WORLD_OWNED_EMBEDDED_TYPES = new Set(["feat", "race", "species", "status", "spellbook", "language"]);
async function markActorItemsAsSynced(actor) {
const updates = actor.items.contents
.filter((item) => !item.getFlag?.(MODULE_ID, "syncedItem"))
.filter((item) => !item.getFlag?.(MODULE_ID, "syncedItem") && !WORLD_OWNED_EMBEDDED_TYPES.has(item.type))
.map((item) => ({
_id: item.id,
[`flags.${MODULE_ID}.syncedItem`]: true,
@@ -1194,7 +1201,19 @@ async function reconcileEmbeddedItems(actor, entry) {
const existing = actor.items.contents.find((item) => item.name === wanted.name
&& item.type === wanted.type && item.getFlag?.(MODULE_ID, "syncedItem"))
|| actor.items.contents.find((item) => item.name === wanted.name
&& item.getFlag?.(MODULE_ID, "syncedItem"));
&& item.getFlag?.(MODULE_ID, "syncedItem") && !WORLD_OWNED_EMBEDDED_TYPES.has(item.type));
// A carried row holding the name of one of the world's own trait or species documents
// — a trait a campaign that synced before #89 still has in its inventory — stands in
// the world as that document: no loot is made after its name, and the document itself
// is let be. Writing it out of the campaign is the campaign's to do, keeping it is the world's.
if (!existing && wanted.type === "loot") {
const worldOwned = actor.items.contents.find((item) => item.name === wanted.name
&& WORLD_OWNED_EMBEDDED_TYPES.has(item.type));
if (worldOwned) {
retainedIds.add(worldOwned.id);
continue;
}
}
if (existing) {
retainedIds.add(existing.id);
const update = { _id: existing.id };
@@ -1220,7 +1239,8 @@ async function reconcileEmbeddedItems(actor, entry) {
}
const staleItemIds = actor.items.contents
.filter((item) => item.getFlag?.(MODULE_ID, "syncedItem") && !retainedIds.has(item.id))
.filter((item) => item.getFlag?.(MODULE_ID, "syncedItem") && !retainedIds.has(item.id)
&& !WORLD_OWNED_EMBEDDED_TYPES.has(item.type))
.map((item) => item.id);
if (staleItemIds.length) await actor.deleteEmbeddedDocuments("Item", staleItemIds);
}

View File

@@ -319,7 +319,10 @@ async function saveSheet() {
<div v-if="error" class="sheet-error">{{ error }}</div>
<main v-show="activeTab === 'abilities'" class="sheet-grid">
<!-- La columna del personatge no penja de cap pestanya: la imatge i el que es mira
d'anada i tornada — classe d'armadura, velocitat, bonificadors i les barres de
cops — es queden a la vista des de qualsevol pestanya de la fitxa. -->
<div class="sheet-layout">
<div class="character-column">
<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')">
@@ -387,146 +390,148 @@ async function saveSheet() {
</section>
</div>
<section class="sheet-panel abilities-panel">
<h2>{{ $t('campaigns.character-sheet.ability-scores') }}</h2>
<div class="ability-grid">
<div v-for="stat in abilityStats" :key="stat.key" class="ability-card">
<span class="ability-label">{{ stat.label }}</span>
<input v-if="editing" v-model.number="form.abilityScores[stat.key]" type="number" min="1" max="30" :aria-label="stat.label">
<strong v-else class="ability-score">{{ form.abilityScores[stat.key] }}</strong>
<span class="ability-modifier">{{ abilityModifier(form.abilityScores[stat.key]) }}</span>
<main v-show="activeTab === 'abilities'" class="sheet-tab-body">
<section class="sheet-panel abilities-panel">
<h2>{{ $t('campaigns.character-sheet.ability-scores') }}</h2>
<div class="ability-grid">
<div v-for="stat in abilityStats" :key="stat.key" class="ability-card">
<span class="ability-label">{{ stat.label }}</span>
<input v-if="editing" v-model.number="form.abilityScores[stat.key]" type="number" min="1" max="30" :aria-label="stat.label">
<strong v-else class="ability-score">{{ form.abilityScores[stat.key] }}</strong>
<span class="ability-modifier">{{ abilityModifier(form.abilityScores[stat.key]) }}</span>
</div>
</div>
</div>
<!-- Les tirades de salvació van just a sota de les característiques, que
són les que les manen: el cercle diu si el personatge hi està entrenat. -->
<h3>{{ $t('campaigns.character-sheet.saving-throws') }}</h3>
<div class="saving-throw-grid">
<button
v-for="stat in abilityStats"
:key="stat.key"
class="proficiency-row"
type="button"
role="switch"
:aria-checked="form.savingThrows[stat.key]"
:disabled="!editing"
@click="toggleProficiency('savingThrows', stat.key)"
>
<span class="proficiency-dot" :class="{ proficient: form.savingThrows[stat.key] }" aria-hidden="true" />
<span class="proficiency-name">{{ $t(`campaigns.character-sheet.abilities.${stat.key}`) }}</span>
<span class="proficiency-modifier">{{ savingThrowModifier(stat) }}</span>
</button>
</div>
</section>
<section class="sheet-panel skills-panel">
<h2>{{ $t('campaigns.character-sheet.skills') }}</h2>
<div class="skill-grid">
<button
v-for="skill in skillList"
:key="skill.key"
class="proficiency-row"
type="button"
role="switch"
:aria-checked="form.skills[skill.key]"
:disabled="!editing"
@click="toggleProficiency('skills', skill.key)"
>
<span class="proficiency-dot" :class="{ proficient: form.skills[skill.key] }" aria-hidden="true" />
<span class="proficiency-name">{{ $t(`campaigns.character-sheet.skill-names.${skill.key}`) }}</span>
<span class="proficiency-ability">{{ skill.ability.toUpperCase() }}</span>
<span class="proficiency-modifier">{{ skillModifier(skill) }}</span>
</button>
</div>
</section>
<section class="sheet-panel proficiencies-panel">
<h2>{{ $t('campaigns.character-sheet.proficiencies') }}</h2>
<textarea v-if="editing" v-model="form.proficiencies" rows="7" :placeholder="$t('campaigns.character-sheet.proficiencies-placeholder')" />
<p v-else class="sheet-copy">{{ form.proficiencies || $t('campaigns.character-sheet.empty-proficiencies') }}</p>
<!-- Les eines i els idiomes tenen llista pròpia; el text de dalt guarda
el que no en té, com les armadures i les armes. -->
<div class="proficiency-lists">
<div class="proficiency-list">
<h3>{{ $t('campaigns.character-sheet.tools') }}</h3>
<textarea v-if="editing" v-model="form.tools" rows="4" :placeholder="$t('campaigns.character-sheet.tools-placeholder')" />
<p v-else class="sheet-copy">{{ form.tools || $t('campaigns.character-sheet.empty-tools') }}</p>
<!-- Les tirades de salvació van just a sota de les característiques, que
són les que les manen: el cercle diu si el personatge hi està entrenat. -->
<h3>{{ $t('campaigns.character-sheet.saving-throws') }}</h3>
<div class="saving-throw-grid">
<button
v-for="stat in abilityStats"
:key="stat.key"
class="proficiency-row"
type="button"
role="switch"
:aria-checked="form.savingThrows[stat.key]"
:disabled="!editing"
@click="toggleProficiency('savingThrows', stat.key)"
>
<span class="proficiency-dot" :class="{ proficient: form.savingThrows[stat.key] }" aria-hidden="true" />
<span class="proficiency-name">{{ $t(`campaigns.character-sheet.abilities.${stat.key}`) }}</span>
<span class="proficiency-modifier">{{ savingThrowModifier(stat) }}</span>
</button>
</div>
<div class="proficiency-list">
<h3>{{ $t('campaigns.character-sheet.languages') }}</h3>
<textarea v-if="editing" v-model="form.languages" rows="4" :placeholder="$t('campaigns.character-sheet.languages-placeholder')" />
<p v-else class="sheet-copy">{{ form.languages || $t('campaigns.character-sheet.empty-languages') }}</p>
</section>
<section class="sheet-panel skills-panel">
<h2>{{ $t('campaigns.character-sheet.skills') }}</h2>
<div class="skill-grid">
<button
v-for="skill in skillList"
:key="skill.key"
class="proficiency-row"
type="button"
role="switch"
:aria-checked="form.skills[skill.key]"
:disabled="!editing"
@click="toggleProficiency('skills', skill.key)"
>
<span class="proficiency-dot" :class="{ proficient: form.skills[skill.key] }" aria-hidden="true" />
<span class="proficiency-name">{{ $t(`campaigns.character-sheet.skill-names.${skill.key}`) }}</span>
<span class="proficiency-ability">{{ skill.ability.toUpperCase() }}</span>
<span class="proficiency-modifier">{{ skillModifier(skill) }}</span>
</button>
</div>
</div>
</section>
</main>
</section>
<main v-show="activeTab === 'inventory'" class="sheet-tab-body">
<section class="sheet-panel inventory-panel">
<div class="panel-title-row">
<h2>{{ $t('campaigns.character-sheet.inventory') }}</h2>
<button v-if="editing" class="sheet-button secondary compact" type="button" @click="addInventoryItem">{{ $t('campaigns.character-sheet.add-item') }}</button>
</div>
<div class="weight-summary">
<span>{{ $t('campaigns.character-sheet.carried-weight') }}</span>
<strong>{{ carriedWeight.toFixed(1) }} / {{ carryingCapacity }} lb</strong>
</div>
<div class="weight-track"><div class="weight-fill" :style="{ width: `${carryPercent}%` }" /></div>
<section class="sheet-panel proficiencies-panel">
<h2>{{ $t('campaigns.character-sheet.proficiencies') }}</h2>
<textarea v-if="editing" v-model="form.proficiencies" rows="7" :placeholder="$t('campaigns.character-sheet.proficiencies-placeholder')" />
<p v-else class="sheet-copy">{{ form.proficiencies || $t('campaigns.character-sheet.empty-proficiencies') }}</p>
<!-- La moneda que el personatge porta a sobre, en les cinc monedes del joc. -->
<h3>{{ $t('campaigns.character-sheet.currency') }}</h3>
<div class="currency-row">
<label v-for="unit in currencyUnits" :key="unit" class="currency-field">
<span>{{ $t(`campaigns.character-sheet.currency-units.${unit}`) }}</span>
<input v-if="editing" v-model.number="form.currency[unit]" type="number" min="0" :aria-label="$t(`campaigns.character-sheet.currency-units.${unit}`)">
<strong v-else>{{ form.currency[unit] }}</strong>
</label>
</div>
<div class="inventory-table-wrap">
<table class="inventory-table">
<thead><tr>
<th><span class="sr-only">{{ $t('campaigns.character-sheet.item-icon') }}</span></th>
<th class="item-name-cell">{{ $t('campaigns.character-sheet.item-name') }}</th>
<th>{{ $t('campaigns.character-sheet.quantity') }}</th>
<th>{{ $t('campaigns.character-sheet.weight-each') }}</th>
<th>{{ $t('campaigns.character-sheet.total-weight') }}</th>
<th v-if="editing"><span class="sr-only">{{ $t('campaigns.character-sheet.actions') }}</span></th>
</tr></thead>
<tbody>
<tr v-for="(item, index) in form.inventory" :key="index">
<td class="item-icon-cell">
<img v-if="item.icon" :src="resolveImage(item.icon)" :alt="$t('campaigns.character-sheet.item-icon')">
<span v-else class="item-icon-blank" aria-hidden="true" />
</td>
<td class="item-name-cell"><input v-if="editing" v-model="item.name" :aria-label="$t('campaigns.character-sheet.item-name')"><span v-else>{{ item.name }}</span></td>
<td><input v-if="editing" v-model.number="item.quantity" type="number" min="1" :aria-label="$t('campaigns.character-sheet.quantity')"><span v-else>{{ item.quantity }}</span></td>
<td><input v-if="editing" v-model.number="item.weight" type="number" min="0" step="0.1" :aria-label="$t('campaigns.character-sheet.weight-each')"><span v-else>{{ Number(item.weight).toFixed(1) }} lb</span></td>
<td>{{ ((Number(item.quantity) || 0) * (Number(item.weight) || 0)).toFixed(1) }} lb</td>
<td v-if="editing"><button class="remove-item" type="button" @click="removeInventoryItem(index)">×</button></td>
</tr>
<tr v-if="form.inventory.length === 0"><td :colspan="editing ? 6 : 5" class="empty-inventory">{{ $t('campaigns.character-sheet.empty-inventory') }}</td></tr>
</tbody>
</table>
</div>
</section>
</main>
<!-- Les eines i els idiomes tenen llista pròpia; el text de dalt guarda
el que no en té, com les armadures i les armes. -->
<div class="proficiency-lists">
<div class="proficiency-list">
<h3>{{ $t('campaigns.character-sheet.tools') }}</h3>
<textarea v-if="editing" v-model="form.tools" rows="4" :placeholder="$t('campaigns.character-sheet.tools-placeholder')" />
<p v-else class="sheet-copy">{{ form.tools || $t('campaigns.character-sheet.empty-tools') }}</p>
</div>
<div class="proficiency-list">
<h3>{{ $t('campaigns.character-sheet.languages') }}</h3>
<textarea v-if="editing" v-model="form.languages" rows="4" :placeholder="$t('campaigns.character-sheet.languages-placeholder')" />
<p v-else class="sheet-copy">{{ form.languages || $t('campaigns.character-sheet.empty-languages') }}</p>
</div>
</div>
</section>
</main>
<main v-show="activeTab === 'traits'" class="sheet-tab-body">
<section class="sheet-panel traits-panel">
<h2>{{ $t('campaigns.character-sheet.traits') }}</h2>
<textarea v-if="editing" v-model="form.traits" rows="12" :placeholder="$t('campaigns.character-sheet.traits-placeholder')" />
<p v-else class="sheet-copy">{{ form.traits || $t('campaigns.character-sheet.empty-traits') }}</p>
</section>
</main>
<main v-show="activeTab === 'inventory'" class="sheet-tab-body">
<section class="sheet-panel inventory-panel">
<div class="panel-title-row">
<h2>{{ $t('campaigns.character-sheet.inventory') }}</h2>
<button v-if="editing" class="sheet-button secondary compact" type="button" @click="addInventoryItem">{{ $t('campaigns.character-sheet.add-item') }}</button>
</div>
<div class="weight-summary">
<span>{{ $t('campaigns.character-sheet.carried-weight') }}</span>
<strong>{{ carriedWeight.toFixed(1) }} / {{ carryingCapacity }} lb</strong>
</div>
<div class="weight-track"><div class="weight-fill" :style="{ width: `${carryPercent}%` }" /></div>
<main v-show="activeTab === 'spells'" class="sheet-tab-body">
<section class="sheet-panel spells-panel">
<h2>{{ $t('campaigns.character-sheet.spells') }}</h2>
<textarea v-if="editing" v-model="form.spells" rows="12" :placeholder="$t('campaigns.character-sheet.spells-placeholder')" />
<p v-else class="sheet-copy">{{ form.spells || $t('campaigns.character-sheet.empty-spells') }}</p>
</section>
</main>
<!-- La moneda que el personatge porta a sobre, en les cinc monedes del joc. -->
<h3>{{ $t('campaigns.character-sheet.currency') }}</h3>
<div class="currency-row">
<label v-for="unit in currencyUnits" :key="unit" class="currency-field">
<span>{{ $t(`campaigns.character-sheet.currency-units.${unit}`) }}</span>
<input v-if="editing" v-model.number="form.currency[unit]" type="number" min="0" :aria-label="$t(`campaigns.character-sheet.currency-units.${unit}`)">
<strong v-else>{{ form.currency[unit] }}</strong>
</label>
</div>
<div class="inventory-table-wrap">
<table class="inventory-table">
<thead><tr>
<th><span class="sr-only">{{ $t('campaigns.character-sheet.item-icon') }}</span></th>
<th class="item-name-cell">{{ $t('campaigns.character-sheet.item-name') }}</th>
<th>{{ $t('campaigns.character-sheet.quantity') }}</th>
<th>{{ $t('campaigns.character-sheet.weight-each') }}</th>
<th>{{ $t('campaigns.character-sheet.total-weight') }}</th>
<th v-if="editing"><span class="sr-only">{{ $t('campaigns.character-sheet.actions') }}</span></th>
</tr></thead>
<tbody>
<tr v-for="(item, index) in form.inventory" :key="index">
<td class="item-icon-cell">
<img v-if="item.icon" :src="resolveImage(item.icon)" :alt="$t('campaigns.character-sheet.item-icon')">
<span v-else class="item-icon-blank" aria-hidden="true" />
</td>
<td class="item-name-cell"><input v-if="editing" v-model="item.name" :aria-label="$t('campaigns.character-sheet.item-name')"><span v-else>{{ item.name }}</span></td>
<td><input v-if="editing" v-model.number="item.quantity" type="number" min="1" :aria-label="$t('campaigns.character-sheet.quantity')"><span v-else>{{ item.quantity }}</span></td>
<td><input v-if="editing" v-model.number="item.weight" type="number" min="0" step="0.1" :aria-label="$t('campaigns.character-sheet.weight-each')"><span v-else>{{ Number(item.weight).toFixed(1) }} lb</span></td>
<td>{{ ((Number(item.quantity) || 0) * (Number(item.weight) || 0)).toFixed(1) }} lb</td>
<td v-if="editing"><button class="remove-item" type="button" @click="removeInventoryItem(index)">×</button></td>
</tr>
<tr v-if="form.inventory.length === 0"><td :colspan="editing ? 6 : 5" class="empty-inventory">{{ $t('campaigns.character-sheet.empty-inventory') }}</td></tr>
</tbody>
</table>
</div>
</section>
</main>
<main v-show="activeTab === 'traits'" class="sheet-tab-body">
<section class="sheet-panel traits-panel">
<h2>{{ $t('campaigns.character-sheet.traits') }}</h2>
<textarea v-if="editing" v-model="form.traits" rows="12" :placeholder="$t('campaigns.character-sheet.traits-placeholder')" />
<p v-else class="sheet-copy">{{ form.traits || $t('campaigns.character-sheet.empty-traits') }}</p>
</section>
</main>
<main v-show="activeTab === 'spells'" class="sheet-tab-body">
<section class="sheet-panel spells-panel">
<h2>{{ $t('campaigns.character-sheet.spells') }}</h2>
<textarea v-if="editing" v-model="form.spells" rows="12" :placeholder="$t('campaigns.character-sheet.spells-placeholder')" />
<p v-else class="sheet-copy">{{ form.spells || $t('campaigns.character-sheet.empty-spells') }}</p>
</section>
</main>
</div>
</div>
</div>
</template>
@@ -550,8 +555,10 @@ async function saveSheet() {
.sheet-button.primary { background: var(--color-link); color: var(--color-background); border-color: var(--color-link); }
.sheet-button:disabled { opacity: .55; cursor: wait; }
.sheet-button.compact { padding: 5px 9px; font-size: 12px; }
.sheet-grid { display: grid; grid-template-columns: minmax(200px, 34%) minmax(0, 1fr) minmax(0, 1fr); grid-template-rows: auto auto auto; gap: 11px; align-items: start; }
.sheet-tab-body { display: block; }
/* El marc de la fitxa: la columna del personatge, sempre a la vista, i al seu costat el contingent
de la pestanya oberta. */
.sheet-layout { display: grid; grid-template-columns: minmax(200px, 34%) minmax(0, 1fr); gap: 11px; align-items: start; }
.sheet-tab-body { grid-column: 2; grid-row: 1; display: flex; flex-direction: column; gap: 11px; min-width: 0; }
/* 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; }
@@ -585,11 +592,9 @@ async function saveSheet() {
.portrait-controls button:disabled { opacity: .55; cursor: wait; }
.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; }
.skills-panel { grid-column: 2 / -1; grid-row: 2; }
.proficiencies-panel { grid-column: 2 / -1; grid-row: 3; }
tornada — classe d'armadura, velocitat, bonificadors i les barres de cops. No penja de
cap pestanya: es queda al seu lloc mentre se'n canvia. */
.character-column { grid-column: 1; grid-row: 1; display: flex; flex-direction: column; gap: 11px; min-width: 0; }
.ability-grid { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 7px; }
.ability-card { min-height: 83px; padding: 8px 5px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); }
.ability-label { font-size: 11px; font-weight: 700; letter-spacing: .08em; opacity: .75; }
@@ -663,8 +668,8 @@ textarea { resize: vertical; width: 100%; min-height: 88px; font-size: 12px; }
.sheet-error { padding: 7px 10px; margin-bottom: 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
@media (max-width: 760px) {
.sheet-grid { grid-template-columns: 1fr; grid-template-rows: none; }
.character-column, .abilities-panel, .skills-panel, .proficiencies-panel { grid-column: 1 / -1; grid-row: auto; }
.sheet-layout { grid-template-columns: 1fr; }
.character-column, .sheet-tab-body { 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; }

View File

@@ -0,0 +1,111 @@
// Tests for Syndria98/dragonroll#91: the column that opens the character sheet — the portrait with
// the armor class, the speed, the bonuses and both pools under it — stays on screen whoever's tab is
// open, instead of being the ability scores tab's own content and disappearing when the sheet moves
// to the inventory, the traits or the spells.
//
// The window is a `.vue` file and the repository root installs no dependencies for the frontend, so
// the template and the styles are read out of the source the way tests/character-sheet-tabs.test.js
// and tests/character-sheet-portrait-column.test.js read them.
//
// 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 template = /<template>([\s\S]*)<\/template>/.exec(sheetSource)?.[1] ?? "";
const TAB_KEYS = ["abilities", "inventory", "traits", "spells"];
const COLUMN = '<div class="character-column">';
function tabBody(key) {
const block = new RegExp(`<main v-show="activeTab === '${key}'"[\\s\\S]*?</main>`).exec(template)?.[0];
assert.ok(block, `expected a body for the ${key} tab`);
return block;
}
// The column, taken whole: it stands ahead of the tab bodies, which are its siblings.
function characterColumn() {
const start = template.indexOf(COLUMN);
const end = template.indexOf('<main v-show="activeTab');
assert.ok(start !== -1 && end > start, "expected the character column ahead of the tab bodies");
return template.slice(start, end);
}
// The classes wrapping a tag, worked out by walking the blocks of the template in order the way a
// browser nests them, so a tab cannot hide the column by wrapping it.
function ancestorsOf(needle) {
const at = template.indexOf(needle);
assert.ok(at !== -1, `expected ${needle} in the template`);
const stack = [];
for (const match of template.matchAll(/<(\/?)(div|main|section|header|nav)\b([^>]*)>/g)) {
if (match.index > at) break;
const [, closed, , attrs] = match;
if (closed) stack.pop();
else if (!attrs.trimEnd().endsWith("/")) {
const classes = /\bclass="([^"]*)"/.exec(attrs);
stack.push(classes ? classes[1].trim().split(/\s+/) : []);
}
}
return stack.slice(0, -1).map((classes) => classes.join(" "));
}
test("the character column belongs to no tab", () => {
const column = characterColumn();
assert.ok(column.includes('class="sheet-portrait"'), "the portrait is part of the column");
assert.ok(column.includes('class="sheet-panel vitals-panel"'), "and so is the panel of readouts and bars");
// Nothing toggles the column: no tab decides whether it shows.
assert.doesNotMatch(column, /v-show=/, "the column never hides behind a tab");
for (const key of TAB_KEYS) {
const body = tabBody(key);
assert.doesNotMatch(body, /class="character-column"/, `the ${key} tab does not own the column`);
assert.doesNotMatch(body, /sheet-portrait|vitals-panel/, `the ${key} tab does not hold the column's contents`);
}
});
test("the column and the tab that is open stand beside each other", () => {
const columnWrappers = ancestorsOf(COLUMN);
assert.equal(columnWrappers.at(-1), "sheet-layout", "the column stands in the sheet's own layout");
for (const key of TAB_KEYS) {
assert.deepEqual(
ancestorsOf(`<main v-show="activeTab === '${key}'"`),
columnWrappers,
`the ${key} tab is a sibling of the column, so it is never wrapped around it`
);
}
const layout = /\.sheet-layout\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
assert.match(layout, /display:\s*grid/, "the layout puts the column and the open tab side by side");
assert.match(
layout,
/grid-template-columns:\s*minmax\(200px,\s*34%\)\s+minmax\(0,\s*1fr\)/,
"the character keeps its own column and the tab has all the room left"
);
const columnRule = /\.character-column\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
assert.match(columnRule, /grid-column:\s*1/, "the character stands in the first column");
const bodyRule = /\.sheet-tab-body\s*\{[^}]*\}/.exec(sheetSource)?.[0] ?? "";
assert.match(bodyRule, /grid-column:\s*2/, "the open tab takes the space beside it");
assert.match(bodyRule, /grid-row:\s*1/, "and on the same row, so switching a tab leaves the column where it was");
});
test("a narrow window stacks the column over the tab instead of hiding it", () => {
const narrow = /@media \(max-width: 760px\)\s*\{([\s\S]*?)\n\}/.exec(sheetSource)?.[1] ?? "";
assert.match(narrow, /\.sheet-layout\s*\{[^}]*grid-template-columns:\s*1fr/, "the two columns become one");
assert.match(
narrow,
/\.character-column,\s*\.sheet-tab-body\s*\{[^}]*grid-column:\s*1 \/ -1;[^}]*grid-row:\s*auto/,
"the column goes over the tab, it does not go away with it"
);
});
test("what stays on screen is what the sheet is read for", () => {
const column = characterColumn();
for (const key of ["armor-class", "speed", "proficiency-bonus", "initiative", "hit-points", "hit-dice"]) {
assert.ok(column.includes(`campaigns.character-sheet.${key}`), `the ${key} stays visible from any tab`);
}
});

View File

@@ -43,7 +43,7 @@ const normalizeActor = fromSource(script, /function normalizeActor\(actor\) \{[\
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.
// The column that stands beside every 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">');

View File

@@ -53,7 +53,6 @@ function tabBody(key) {
test("every tab shows only its own content and hides the others", () => {
const abilities = tabBody("abilities");
assert.match(abilities, /class="sheet-portrait"/, "the portrait stays with ability scores");
assert.match(abilities, /class="sheet-panel abilities-panel"/);
assert.match(abilities, /class="sheet-panel proficiencies-panel"/, "the proficiencies ride with the ability scores");
for (const other of ["inventory-panel", "traits-panel", "spells-panel"]) {
@@ -63,7 +62,12 @@ test("every tab shows only its own content and hides the others", () => {
for (const [key, panel] of [["inventory", "inventory-panel"], ["traits", "traits-panel"], ["spells", "spells-panel"]]) {
const body = tabBody(key);
assert.ok(body.includes(panel), `the ${key} tab shows the ${panel}`);
assert.doesNotMatch(body, /class="sheet-portrait"/);
}
// #91 took the character column out of the tabs: it stands beside every one of them, so no tab
// body holds the portrait (see tests/character-sheet-persistent-column.test.js).
for (const key of ["abilities", "inventory", "traits", "spells"]) {
assert.doesNotMatch(tabBody(key), /class="sheet-portrait"/, `the portrait is not the ${key} tab's to hide`);
}
// the panels are toggled, not unmounted, so editing on one tab and flipping away keeps the draft

View File

@@ -0,0 +1,522 @@
// Tests for Syndria98/dragonroll#89: on the character sheet traits and items were all
// displayed together and the icons did not load. The world's mapper put every embedded
// document that was not a class, subclass, background or spell into the character's
// inventory — so its traits (feat items) and its species (the race item) stood in the
// inventory list beside the gear, while the sheet already shows both in fields of their
// own. And a world image that arrives as a Foundry path — the bridge's snapshot and older
// modules send those, where the module sends absolute URLs — was read against Dragonroll's
// uploads folder, where nothing of that name is, so nothing loaded.
//
// The mapper is plain CommonJS and is required for real. The writers run in a stubbed
// `require` against fake models, like tests/foundry-force-import.test.js runs them. And
// since the campaign's inventory no longer claims trait and species documents, the module
// must stop deleting ones earlier syncs marked as its own: the Foundry module goes into a
// `node:vm` context holding stubbed Foundry globals with fake timers, like
// tests/foundry-actor-details.test.js, so what writing a character leaves behind is observable.
//
// 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 MODULE_ID = "dragonroll-foundry";
// --- What the world's mapper keeps where -------------------------------------------------
const { foundryActorToCharacter } = require(path.join(__dirname, "..", "backend", "src", "services", "actor-foundry.js"));
test("traits and species stand in their own fields, not among the carried items", () => {
const character = foundryActorToCharacter({
name: "Thalia",
system: { details: {} },
items: [
{ name: "Longsword", type: "weapon", img: "http://vtt.test/icons/sword.svg", system: { quantity: 1, weight: { value: 3 } } },
{ name: "Rope", type: "equipment", system: { quantity: 2 } },
{ name: "Darkvision", type: "feat", system: { featType: "trs", description: { value: "<p>See in the dark.</p>" } } },
{ name: "Human", type: "race" },
{ name: "Spellbook", type: "spellbook" },
{ name: "Magic Missile", type: "spell" },
{ name: "Fighter", type: "class" },
{ name: "Oracle", type: "subclass" },
{ name: "Soldier", type: "background" },
],
});
assert.deepEqual(character.inventory.map((item) => item.name), ["Longsword", "Rope"],
"the inventory holds what the character carries, and nothing else");
assert.deepEqual(character.inventory[0],
{ name: "Longsword", quantity: 1, weight: 3, icon: "http://vtt.test/icons/sword.svg" });
assert.equal(character.traits, "Darkvision\nSee in the dark.", "the feat is read as a trait, where the sheet shows it");
assert.equal(character.spells, "Magic Missile", "and the spell where its tab shows it");
});
test("gear of a type the mapper has never seen is still carried", () => {
const character = foundryActorToCharacter({
name: "Thalia",
items: [{ name: "Strange Relic", type: "loot", system: { quantity: 1 } }],
});
assert.deepEqual(character.inventory.map((item) => item.name), ["Strange Relic"],
"only the listed non-gear types are let out of the inventory");
});
// --- The writers read a world's paths off the world's address ----------------------------
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 and $or.
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 writers against fake models. `settings` is what the campaign keeps — the world
// address the icons are loaded from stands in it, as it does in the real one.
function loadFoundryWriters({ seed = {}, settings } = {}) {
const campaign = { _id: "campaign-1", id: "campaign-1", foundryWorldId: "world-1", ...(settings ? { settings } : {}) };
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 (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.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("a world image that arrives as a path is stored as the address the sheet can load", async () => {
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000/" } } });
await sync.writers.saveFoundryActor(sync.campaign, {
_id: "actor-1",
name: "Thalia",
type: "character",
img: "icons/actors/thalia.svg",
items: [
{ name: "Torch", type: "loot", img: "icons/tools/torch torch.svg", system: { quantity: 2 } },
{ name: "Darkvision", type: "feat", img: "icons/svg/eye.svg" },
],
});
const actor = sync.models["../models/Actor"].rows[0];
assert.equal(actor.image, "http://vtt.test:30000/icons/actors/thalia.svg", "the portrait is read off the world's address");
assert.deepEqual(actor.inventory.map((item) => item.name), ["Torch"], "the feat is not carried into the inventory");
assert.equal(actor.inventory[0].icon, "http://vtt.test:30000/icons/tools/torch%20torch.svg", "and the gear's icon is");
});
test("the absolute addresses the module sends travel as they are", async () => {
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000" } } });
await sync.writers.saveFoundryActor(sync.campaign, {
_id: "actor-1",
name: "Thalia",
img: "http://elsewhere.test/portraits/thalia.png",
items: [{ name: "Torch", type: "loot", img: "data:image/png;base64,TgA=" }],
});
const actor = sync.models["../models/Actor"].rows[0];
assert.equal(actor.image, "http://elsewhere.test/portraits/thalia.png");
assert.equal(actor.inventory[0].icon, "data:image/png;base64,TgA=");
});
test("a campaign with no world address keeps the path as it came", async () => {
const sync = loadFoundryWriters();
await sync.writers.saveFoundryActor(sync.campaign, {
_id: "actor-1", name: "Thalia", img: "icons/actors/thalia.svg",
});
assert.equal(sync.models["../models/Actor"].rows[0].image, "icons/actors/thalia.svg",
"with no world to read it against, nothing is invented for it");
});
test("a world item's icon is read off the world's address the same way", async () => {
const sync = loadFoundryWriters({ settings: { integrations: { foundryUrl: "http://vtt.test:30000" } } });
await sync.writers.saveFoundryItem(sync.campaign, {
_id: "item-1", name: "Longsword", type: "weapon", img: "icons/equipment/sword.svg",
});
const item = sync.models["../models/Item"].rows[0];
assert.equal(item.image, "http://vtt.test:30000/icons/equipment/sword.svg");
assert.equal(item.foundryImage, "http://vtt.test:30000/icons/equipment/sword.svg",
"the icon the item window offers back is the loadable one too");
});
// --- The module leaves the world's own documents alone ------------------------------------
function makeStubItem(id, { name, type, system = {}, flags = {} }) {
return {
_id: id,
id,
name,
type,
system,
flags,
parent: { documentName: "Actor" },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
toObject() {
return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: this.flags };
},
};
}
function writeDotted(target, data) {
for (const [key, value] of Object.entries(data)) {
const parts = key.split(".");
const last = parts.pop();
let node = target;
for (const part of parts) node = node[part] ??= {};
node[last] = value;
}
}
let stubCounter = 0;
function makeStubActor(name, { type = "character", system = {}, flags = {}, items = [] } = {}) {
stubCounter += 1;
const id = `actor-${stubCounter}`;
const contents = items.map((item, index) => makeStubItem(item._id || `embedded-${stubCounter}-${index}`, item));
const actor = {
id,
name,
type,
documentName: "Actor",
img: "icons/svg/mystery-man.svg",
system,
flags,
items: { contents },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
async update(data) {
writeDotted(this, data);
return this;
},
async updateEmbeddedDocuments(documentName, updates) {
for (const update of updates) {
const item = contents.find((candidate) => candidate.id === update._id);
if (item) writeDotted(item, update);
}
return updates.map((update) => contents.find((candidate) => candidate.id === update._id));
},
async createEmbeddedDocuments(documentName, datas) {
const created = datas.map((data) => {
const item = makeStubItem(`embedded-${stubCounter}-${contents.length}`, data);
contents.push(item);
return item;
});
return created;
},
async deleteEmbeddedDocuments(documentName, ids) {
for (const id of ids) {
const index = contents.findIndex((item) => item.id === id);
if (index >= 0) contents.splice(index, 1);
}
return ids;
},
toObject() {
return {
_id: this.id,
name: this.name,
type: this.type,
img: this.img,
flags: this.flags,
system: this.system,
};
},
};
return actor;
}
function makeWorld({ actors = [], remoteActors = [] } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
nextTimerId: 1,
logs: [],
};
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
const sandbox = {
console: {
log() {},
info() {},
warn: (...args) => state.logs.push(args.map(String).join(" ")),
error: (...args) => state.logs.push(args.map(String).join(" ")),
},
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: { notifications: { info() {}, warn() {}, error() {} } },
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); },
},
setTimeout: (fn, delay = 0) => {
const timerId = state.nextTimerId++;
state.timers.set(timerId, { fn, delay });
return timerId;
},
clearTimeout: (timerId) => state.timers.delete(timerId),
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({ href, method: options.method, body: options.body ? JSON.parse(options.body) : null });
if (href.includes("foundry/sync/characters")) return { ok: true, status: 200, json: async () => ({ status: "ok", actors: remoteActors }) };
if (href.includes("foundry/sync/items")) return { ok: true, status: 200, json: async () => ({ status: "ok", items: [] }) };
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Item: { async create() { return null; } },
Actor: {
async create(data) {
const actor = makeStubActor(data.name, {
type: data.type,
system: structuredClone(data.system || {}),
flags: structuredClone(data.flags || {}),
items: (data.items || []).map((item) => ({ name: item.name, type: item.type, system: item.system })),
});
actors.push(actor);
return actor;
},
},
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: actors, get: (actorId) => actors.find((actor) => actor.id === actorId) },
items: { contents: [], get: () => null },
folders: { contents: [], get: () => null },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(read("dragonroll-foundry", "scripts", "api.js"), sandbox);
state.game = sandbox.game;
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
// World start: the actors are pushed, then the campaign's characters are applied.
state.start = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
return state;
};
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await drain();
};
state.runTimers = async () => {
for (let round = 0; round < 6; round += 1) {
if (!state.timers.size && round > 2) break;
const due = [...state.timers.values()];
state.timers.clear();
for (const timer of due) await timer.fn();
await drain();
}
};
state.itemNames = (actor) => actor.items.contents.map((item) => [item.type, item.name]);
state.actorPushes = () => state.requests
.filter((request) => request.href.includes("foundry/sync/snapshot"))
.map((request) => request.body.actors[0]);
return state;
}
// The campaign's character for `actor`, holding what Dragonroll keeps for it.
function campaignCharacter(actor, over = {}) {
return {
_id: "dr-actor-1",
name: "Thalia",
type: "character",
species: "",
className: "",
subclass: "",
level: 1,
background: "",
challengeRating: "",
description: "",
image: "",
abilityScores: {},
armorClass: 10,
speed: 30,
traits: "",
proficiencies: "",
spells: "",
inventory: [],
foundryActorId: actor?.id ?? null,
...over,
};
}
test("a trait row an older campaign left in the inventory does not become a loot duplicate", async () => {
// A campaign that synced before #89 still carries its world's traits as inventory
// rows. Writing the character must neither make a piece of loot after a trait's name
// nor touch the world's feat it holds that name — the row is the campaign's to write
// off, and the document is the world's to keep.
const actor = makeStubActor("Thalia", {
system: { details: {} },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [{ _id: "feat-1", name: "Darkvision", type: "feat", system: { featType: "trs" } }],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, {
traits: "Darkvision\nSee in the dark.",
inventory: [{ name: "Darkvision", quantity: 1, weight: 0 }],
})],
}).start();
assert.deepEqual(world.itemNames(actor), [["feat", "Darkvision"]],
"no gear made after the trait's name, and the feat stands where it was");
assert.equal(actor.items.contents[0].system.quantity, undefined, "the world's feat is not written as gear");
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("writing the character leaves the world's trait and species documents where they stand", async () => {
// An earlier sync marked everything in the actor as its own. The campaign no longer
// carries traits and species in the inventory, so those marks must not cost the world
// its documents — while loot the campaign truly dropped still goes.
const actor = makeStubActor("Thalia", {
system: { details: {} },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: "feat-1", name: "Darkvision", type: "feat", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "race-1", name: "Human", type: "race", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "loot-old", name: "Torch", type: "loot", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, {
species: "Human",
traits: "Darkvision\nSee in the dark.",
inventory: [{ name: "Rations", quantity: 1, weight: 0.5 }],
})],
}).start();
assert.deepEqual(world.itemNames(actor), [
["feat", "Darkvision"],
["race", "Human"],
["loot", "Rations"],
], "the trait and the species survive, the carried gear follows the campaign");
assert.equal(actor.system.details.race, "race-1", "the species reference still resolves to the surviving item");
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("the snapshot marks the carried gear and no longer the world's own documents", async () => {
const actor = makeStubActor("Grimnir", {
system: { details: {} },
items: [
{ name: "Longsword", type: "weapon" },
{ name: "Darkvision", type: "feat" },
{ name: "Giant", type: "race" },
],
});
await makeWorld({ actors: [actor], remoteActors: [] }).start();
const [sword, feat, race] = actor.items.contents;
assert.equal(sword.getFlag(MODULE_ID, "syncedItem"), true, "the gear the campaign carries is marked as its own");
assert.equal(feat.getFlag(MODULE_ID, "syncedItem"), undefined, "a trait is not");
assert.equal(race.getFlag(MODULE_ID, "syncedItem"), undefined, "neither is a species");
});
test("an actor snapshot still sends the feats its traits are made of", async () => {
// Leaving feats out of the inventory must not leave them out of the snapshot: they are
// what the campaign's traits tab reads.
const actor = makeStubActor("Thalia", {
system: { details: {} },
items: [{ name: "Darkvision", type: "feat", system: { featType: "trs" } }],
});
const world = await makeWorld({ actors: [actor], remoteActors: [] }).start();
const sent = world.actorPushes().at(-1);
assert.deepEqual(sent.items.map((item) => [item.type, item.name]), [["feat", "Darkvision"]],
"the feat still travels with its actor, as the traits text is read off it");
});

View File

@@ -280,6 +280,7 @@ function loadFoundryWriters({ seed = {} } = {}) {
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 (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};

View File

@@ -141,6 +141,7 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};