Merge pull request 'Fix #35: Dragonroll frontend: item modifications' (#39) from ai/issue-35 into master
Some checks failed
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Has been cancelled

Reviewed-on: #39
This commit was merged in pull request #39.
This commit is contained in:
2026-10-14 22:23:48 +00:00
15 changed files with 404 additions and 20 deletions

View File

@@ -17,6 +17,12 @@ const ItemSchema = new Schema({
weight: { type: Number, min: 0 }, weight: { type: Number, min: 0 },
properties: { type: String, default: '' }, properties: { type: String, default: '' },
description: { type: String, default: '' }, description: { type: String, default: '' },
// Item icon: an uploaded filename served from /api/public, or a full URL
// (Foundry sends its own icon as one).
image: { type: String, default: '' },
// The icon Foundry last sent for this item, kept even after the user picks
// their own so Dragonroll can still offer Foundry's back.
foundryImage: { type: String, default: '' },
campaign: { campaign: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: 'Campaign', ref: 'Campaign',

View File

@@ -109,6 +109,9 @@ async function saveFoundryItem(campaign, source, fullSync = false) {
item.foundryItemId = foundryItemId; item.foundryItemId = foundryItemId;
if (!fullSync || item.isNew) Object.assign(item, fields); if (!fullSync || item.isNew) Object.assign(item, fields);
// Foundry's own icon is kept on every save, not only when the edits above
// land: the item window offers it back after the user picked their own.
if (fields.image) item.foundryImage = fields.image;
if (!item.foundryNames.includes(fields.name)) { if (!item.foundryNames.includes(fields.name)) {
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES); item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
} }

View File

@@ -1,6 +1,8 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const upload = require('../services/storage');
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Item = require('../models/Item'); const Item = require('../models/Item');
@@ -44,7 +46,7 @@ router.post('/create', async (req, res) => {
router.post('/update', async (req, res) => { router.post('/update', async (req, res) => {
try { try {
const { id, name, category, rarity, quantity, weight, properties, description } = req.body; const { id, name, category, rarity, quantity, weight, properties, description, image } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' }); if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const item = await Item.findById(id); const item = await Item.findById(id);
@@ -58,6 +60,7 @@ router.post('/update', async (req, res) => {
if (weight !== undefined && weight !== '') item.weight = Number(weight); if (weight !== undefined && weight !== '') item.weight = Number(weight);
if (properties !== undefined) item.properties = properties; if (properties !== undefined) item.properties = properties;
if (description !== undefined) item.description = description; if (description !== undefined) item.description = description;
if (image !== undefined) item.image = String(image);
await item.save(); await item.save();
res.json({ status: 'ok', item }); res.json({ status: 'ok', item });
@@ -67,6 +70,25 @@ router.post('/update', async (req, res) => {
} }
}); });
// Upload item image post
router.post("/upload-image", upload.single("image"), async (req, res) => {
try {
const itemId = req.query.item || req.body.item;
if (!itemId || !req.file) return res.json({ status: 'error', msg: 'errors.missing-data' });
const item = await Item.findById(itemId);
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' });
item.image = req.file.filename;
await item.save();
res.json({ status: "ok", msg: "uploaded", item });
} catch (err) {
console.error(err);
res.json({ status: "error", msg: "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

@@ -101,7 +101,9 @@ function foundryItemToItemData(foundryItem) {
quantity: Math.max(1, Math.trunc(numberOr(system.quantity, 1))), quantity: Math.max(1, Math.trunc(numberOr(system.quantity, 1))),
weight: Math.max(0, numberOr(system.weight?.value ?? system.weight, 0)), weight: Math.max(0, numberOr(system.weight?.value ?? system.weight, 0)),
properties: foundryItemProperties(foundryItem), properties: foundryItemProperties(foundryItem),
description: plainText(system.description?.value ?? system.description) description: plainText(system.description?.value ?? system.description),
// The module sends Foundry's icon as an absolute URL, like actors do.
image: asText(foundryItem.img || foundryItem.image)
}; };
} }

View File

@@ -461,7 +461,9 @@ function dragonrollActorId(actor) {
function serializeFoundryActor(actor) { function serializeFoundryActor(actor) {
const data = { const data = {
...toPlainData(actor), ...toPlainData(actor),
items: actor.items?.contents?.map(toPlainData) || [], // Embedded items go through serializeFoundryItem so their icons become
// absolute URLs too: Dragonroll renders them outside of Foundry.
items: (actor.items?.contents?.map(serializeFoundryItem) || []).filter(Boolean),
}; };
if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) { if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) {
data.img = new URL(data.img, window.location.origin).toString(); data.img = new URL(data.img, window.location.origin).toString();
@@ -760,6 +762,7 @@ function makeFoundryItemData(entry) {
const data = { const data = {
name: String(entry.name || "").trim(), name: String(entry.name || "").trim(),
type, type,
img: getDragonrollImageUrl(entry.image) || undefined,
system: { system: {
quantity: Number(entry.quantity) || 1, quantity: Number(entry.quantity) || 1,
weight: Number(entry.weight) || 0, weight: Number(entry.weight) || 0,
@@ -773,13 +776,18 @@ function makeFoundryItemData(entry) {
} }
function foundryItemUpdateData(entry) { function foundryItemUpdateData(entry) {
return { const updates = {
name: String(entry.name || "").trim(), name: String(entry.name || "").trim(),
"system.quantity": Number(entry.quantity) || 1, "system.quantity": Number(entry.quantity) || 1,
"system.weight": Number(entry.weight) || 0, "system.weight": Number(entry.weight) || 0,
"system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common", "system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common",
"system.description.value": entry.description || "", "system.description.value": entry.description || "",
}; };
// An icon the campaign picked in Dragonroll travels back to Foundry; no icon
// there means leave the world's own choice alone, not erase it.
const image = getDragonrollImageUrl(entry.image);
if (image) updates.img = image;
return updates;
} }
async function applyDragonrollItem(item, entry) { async function applyDragonrollItem(item, entry) {

View File

@@ -26,7 +26,6 @@ const sidebarCollapsed = ref(false);
const activeSection = ref('notes'); const activeSection = ref('notes');
const isDragOverSidebar = ref(false); const isDragOverSidebar = ref(false);
const expandedFolderIds = ref([]); const expandedFolderIds = ref([]);
const expandedEntryIds = ref([]);
const nestedNoteListRef = ref(null); const nestedNoteListRef = ref(null);
let entryRefreshInterval; let entryRefreshInterval;
@@ -287,12 +286,6 @@ function showEntryMenu(entry, entityType) {
ShowContextMenu(menuItems); ShowContextMenu(menuItems);
} }
function toggleEntryDetails(entryId) {
expandedEntryIds.value = expandedEntryIds.value.includes(entryId)
? expandedEntryIds.value.filter((id) => id !== entryId)
: [...expandedEntryIds.value, entryId];
}
async function openCharacterSheet(actor) { async function openCharacterSheet(actor) {
const existingWindowId = GetFirstWindowId('character_sheet'); const existingWindowId = GetFirstWindowId('character_sheet');
if (existingWindowId !== undefined) { if (existingWindowId !== undefined) {
@@ -302,6 +295,16 @@ async function openCharacterSheet(actor) {
CreateWindow('character_sheet', { actor }); CreateWindow('character_sheet', { actor });
} }
// Clicking an item opens its window, like a character does with its sheet.
async function openItemSheet(item) {
const existingWindowId = GetFirstWindowId('item_sheet');
if (existingWindowId !== undefined) {
ClearWindow({ id: existingWindowId });
await nextTick();
}
CreateWindow('item_sheet', { item });
}
// Maps are anchored on the note container instead of opening a window: the notes that were open // Maps are anchored on the note container instead of opening a window: the notes that were open
// stay open, and the sidebar's notes/maps buttons switch between the two. // stay open, and the sidebar's notes/maps buttons switch between the two.
function openMapViewer(map) { function openMapViewer(map) {
@@ -498,17 +501,12 @@ onBeforeUnmount(() => {
<div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div> <div v-if="loadingEntries" class="sidebar-state">{{ t('campaigns.states.loading') }}</div>
<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" @click="openItemSheet(item)" @keydown.enter="openItemSheet(item)" @keydown.space.prevent="openItemSheet(item)" @contextmenu.prevent="showEntryMenu(item, 'item')">
<span class="entity-entry-name-row"> <span class="entity-entry-name-row">
<span class="entity-entry-name">{{ item.name }}</span> <span class="entity-entry-name">{{ item.name }}</span>
<span v-if="item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span> <span v-if="item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span>
</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)">
<span v-if="item.weight !== undefined" class="entity-entry-description">{{ item.weight }} lb</span>
<span v-if="item.properties" class="entity-entry-description">{{ item.properties }}</span>
<span v-if="item.description" class="entity-entry-description">{{ item.description }}</span>
</template>
</div> </div>
</template> </template>

View File

@@ -0,0 +1,213 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
import WindowHandle from './partials/WindowHandle.vue';
import Server, { getBaseUrl } from '~/services/Server';
import { emitter } from '~/services/Emitter';
const props = defineProps(['data']);
const id = props.data.id;
const itemId = props.data.item?._id;
const handle = ref(null);
const wrapper = ref(null);
const error = ref('');
const uploadingIcon = ref(false);
const applyingFoundryIcon = ref(false);
const photoInput = ref(null);
const { t } = useI18n();
function normalizeItem(item) {
return {
name: item?.name ?? '',
category: item?.category ?? 'adventuring-gear',
rarity: item?.rarity ?? 'common',
quantity: Number(item?.quantity ?? 1),
weight: item?.weight ?? '',
properties: item?.properties ?? '',
description: item?.description ?? '',
image: item?.image ?? '',
foundryItemId: item?.foundryItemId ?? '',
foundryImage: item?.foundryImage ?? ''
};
}
const form = ref(normalizeItem(props.data.item));
onMounted(() => {
Top(wrapper);
SetupHandle(id, handle);
SetSize(id, { width: 460, height: 560 });
ResetPosition(id, 'center');
});
onBeforeUnmount(() => ClearWindow({ type: 'item_sheet' }));
// The sidebar keeps this entry fresh (Foundry sync lands in the background);
// follow along unless the window is mid-icon-upload.
function handleItemSync({ entityType, entry }) {
if (entityType !== 'item' || entry?._id !== itemId || uploadingIcon.value) return;
form.value = normalizeItem(entry);
}
onMounted(() => emitter.on('campaign-entry-updated', handleItemSync));
onBeforeUnmount(() => emitter.off('campaign-entry-updated', handleItemSync));
const imageUrl = computed(() => {
if (!form.value.image) return '';
return /^(https?:|data:|\/\/)/i.test(form.value.image)
? form.value.image
: `${getBaseUrl()}/public/${form.value.image}`;
});
const canUseFoundryIcon = computed(() => Boolean(form.value.foundryImage) && form.value.foundryImage !== form.value.image);
async function updateItem(payload) {
const response = await Server().post('/item/update', { id: itemId, ...payload });
if (response.data.status !== 'ok') return false;
form.value = normalizeItem(response.data.item);
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
return true;
}
function pickIcon() {
photoInput.value?.click();
}
async function onIconSelected(event) {
const file = event.target.files?.[0];
event.target.value = '';
if (!file || uploadingIcon.value) return;
uploadingIcon.value = true;
error.value = '';
try {
const formData = new FormData();
formData.append('image', file);
const response = await Server().post(`/item/upload-image?item=${itemId}`, formData, {
headers: { "Content-Type": "multipart/form-data" }
});
if (response.data.status !== 'ok') {
error.value = t('campaigns.item.sheet.upload-error');
return;
}
form.value = normalizeItem(response.data.item);
emitter.emit('campaign-entry-updated', { entityType: 'item', entry: response.data.item });
} catch (requestError) {
error.value = t('campaigns.item.sheet.upload-error');
} finally {
uploadingIcon.value = false;
}
}
// "Fetch from Foundry's icons": the module keeps the world's own icon on the
// item, so this just switches back to it.
async function useFoundryIcon() {
if (!canUseFoundryIcon.value || applyingFoundryIcon.value) return;
applyingFoundryIcon.value = true;
error.value = '';
try {
const done = await updateItem({ image: form.value.foundryImage });
if (!done) error.value = t('campaigns.item.sheet.save-error');
} catch (requestError) {
error.value = t('campaigns.item.sheet.save-error');
} finally {
applyingFoundryIcon.value = false;
}
}
async function removeIcon() {
if (!form.value.image) return;
error.value = '';
try {
const done = await updateItem({ image: '' });
if (!done) error.value = t('campaigns.item.sheet.save-error');
} catch (requestError) {
error.value = t('campaigns.item.sheet.save-error');
}
}
</script>
<template>
<div class="window-wrapper item-window" :id="'window-wrapper-' + id" ref="wrapper">
<WindowHandle :window="id" ref="handle" />
<div class="item-body">
<header class="item-hero">
<div class="item-icon" :class="{ empty: !form.image }">
<img v-if="form.image" :src="imageUrl" :alt="$t('campaigns.item.sheet.icon')">
<span v-else aria-hidden="true">{{ form.name.slice(0, 1).toUpperCase() }}</span>
</div>
<div class="item-identity">
<h1>{{ form.name }}</h1>
<div class="item-tags">
<span class="item-tag">{{ $t(`campaigns.item.categories.${form.category}`) }}</span>
<span class="item-tag">{{ $t(`campaigns.item.rarities.${form.rarity}`) }}</span>
<span v-if="form.foundryItemId" class="item-tag synced">{{ $t('campaigns.synced') }}</span>
</div>
</div>
</header>
<div v-if="error" class="item-error">{{ error }}</div>
<div class="icon-controls">
<button class="sheet-button" type="button" :disabled="uploadingIcon" @click="pickIcon">
{{ uploadingIcon
? $t('campaigns.item.sheet.uploading')
: (form.image ? $t('campaigns.item.sheet.change-icon') : $t('campaigns.item.sheet.choose-icon')) }}
</button>
<button v-if="canUseFoundryIcon" class="sheet-button secondary" type="button" :disabled="applyingFoundryIcon" @click="useFoundryIcon">
{{ $t('campaigns.item.sheet.foundry-icon') }}
</button>
<button v-if="form.image" class="sheet-button secondary" type="button" :disabled="uploadingIcon" :aria-label="$t('campaigns.item.sheet.remove-icon')" @click="removeIcon">×</button>
<input ref="photoInput" class="photo-input" type="file" accept="image/*" @change="onIconSelected">
</div>
<dl class="item-facts">
<div class="item-fact">
<dt>{{ $t('campaigns.item.quantity') }}</dt>
<dd>{{ form.quantity }}</dd>
</div>
<div v-if="form.weight !== '' && form.weight !== undefined" class="item-fact">
<dt>{{ $t('campaigns.item.weight') }}</dt>
<dd>{{ Number(form.weight).toFixed(1) }} lb</dd>
</div>
</dl>
<section v-if="form.properties" class="item-section">
<h2>{{ $t('campaigns.item.properties') }}</h2>
<p class="item-copy">{{ form.properties }}</p>
</section>
<section class="item-section">
<h2>{{ $t('campaigns.fields.description') }}</h2>
<p class="item-copy">{{ form.description || $t('campaigns.item.sheet.no-description') }}</p>
</section>
</div>
</div>
</template>
<style scoped>
.item-window { min-width: 0; min-height: 0; }
.item-body { width: 100%; min-height: 0; flex: 1; overflow: auto; padding: 14px 16px 16px; box-sizing: border-box; }
.item-hero { display: flex; align-items: center; gap: 13px; padding: 2px 2px 13px; margin-bottom: 11px; border-bottom: 1px solid var(--color-border); }
.item-icon { width: 64px; height: 64px; flex: 0 0 64px; display: grid; place-items: center; overflow: hidden; border-radius: 10px; border: 1px solid var(--color-border); background: var(--color-background-soft); color: var(--color-link); font: 30px MrEavesRemake; }
.item-icon.empty { border-style: dashed; }
.item-icon img { width: 100%; height: 100%; object-fit: contain; }
.item-identity { min-width: 0; }
.item-identity h1 { margin: 0 0 6px; font: 24px MrEavesRemake; overflow-wrap: anywhere; }
.item-tags { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
.item-tag { padding: 3px 9px; border: 1px solid var(--color-border); border-radius: 999px; background: var(--color-background-soft); font-size: 12px; opacity: .9; }
.item-tag.synced { font-size: 10px; letter-spacing: .04em; text-transform: uppercase; opacity: .6; }
.item-error { padding: 7px 10px; margin-bottom: 10px; border-radius: 6px; color: var(--color-red); background: var(--color-background-soft); font-size: 12px; }
.icon-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; margin-bottom: 13px; }
.sheet-button { border: 1px solid var(--color-border); border-radius: 7px; padding: 7px 12px; background: var(--color-background-soft); color: var(--color-text); cursor: pointer; white-space: nowrap; font-size: 13px; }
.sheet-button:hover { background: var(--color-button-hover); }
.sheet-button:disabled { opacity: .55; cursor: wait; }
.photo-input { display: none; }
.item-facts { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 13px; }
.item-fact { flex: 1 1 120px; min-width: 0; padding: 9px 11px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-background-soft); }
.item-fact dt { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; opacity: .72; }
.item-fact dd { margin: 3px 0 0; font: 17px MrEavesRemake; }
.item-section { padding: 11px 13px; margin: 0 0 10px; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-background-light); }
.item-section h2 { margin: 0 0 8px; padding-bottom: 6px; border-bottom: 1px solid var(--color-border); font: 15px MrEavesRemake; letter-spacing: .03em; }
.item-copy { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; line-height: 1.45; opacity: .85; }
</style>

View File

@@ -71,6 +71,12 @@ const defWindows = {
close: () => ClearWindow({type: 'character_sheet'}), close: () => ClearWindow({type: 'character_sheet'}),
movable: true movable: true
}, },
item_sheet: {
title: 'windows.item-sheet',
component: () => import('~/components/windows/ItemSheetWindow.vue'),
close: () => ClearWindow({type: 'item_sheet'}),
movable: true
},
create_map: { create_map: {
title: 'windows.create-map', title: 'windows.create-map',
component: () => import('~/components/windows/CreateMapWindow.vue'), component: () => import('~/components/windows/CreateMapWindow.vue'),

View File

@@ -62,6 +62,12 @@
"new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.", "new": "Objecte nou", "edit": "Edita l'objecte", "foundry-sync-note": "Els canvis en aquest objecte també s'apliquen al món del Foundry vinculat.",
"category": "Categoria", "rarity": "Raresa", "quantity": "Quantitat", "category": "Categoria", "rarity": "Raresa", "quantity": "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",
"sheet": {
"icon": "Icona de l'objecte", "choose-icon": "Tria la teva pròpia icona", "change-icon": "Canvia la icona",
"uploading": "Pujant...", "upload-error": "No s'ha pogut pujar aquesta icona.",
"foundry-icon": "Fes servir la icona del Foundry", "remove-icon": "Treu la icona", "save-error": "No s'ha pogut desar aquest objecte.",
"no-description": "Sense descripció afegida."
},
"categories": { "categories": {
"weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura", "weapon": "Arma", "armor": "Armadura", "shield": "Escut", "adventuring-gear": "Equip d'aventura",
"magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre" "magic-item": "Objecte màgic", "consumable": "Consumible", "tool": "Eina", "treasure": "Tresor", "other": "Altre"

View File

@@ -8,5 +8,6 @@
"create-campaign": "Crear campanya", "create-campaign": "Crear campanya",
"create-map": "Crear mapa", "create-map": "Crear mapa",
"map-viewer": "Mapa", "map-viewer": "Mapa",
"pinned-note": "Nota fixada" "pinned-note": "Nota fixada",
"item-sheet": "Objecte"
} }

View File

@@ -66,6 +66,12 @@
"new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.", "new": "New item", "edit": "Edit item", "foundry-sync-note": "Changes to this item are also applied in the linked Foundry world.",
"category": "Category", "rarity": "Rarity", "quantity": "Quantity", "category": "Category", "rarity": "Rarity", "quantity": "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",
"sheet": {
"icon": "Item icon", "choose-icon": "Choose your own icon", "change-icon": "Change icon",
"uploading": "Uploading...", "upload-error": "Unable to upload this icon.",
"foundry-icon": "Use Foundry icon", "remove-icon": "Remove icon", "save-error": "Unable to save this item.",
"no-description": "No description added."
},
"categories": { "categories": {
"weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear", "weapon": "Weapon", "armor": "Armor", "shield": "Shield", "adventuring-gear": "Adventuring gear",
"magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other" "magic-item": "Magic item", "consumable": "Consumable", "tool": "Tool", "treasure": "Treasure", "other": "Other"

View File

@@ -8,5 +8,6 @@
"create-campaign": "Create Campaign", "create-campaign": "Create Campaign",
"create-map": "Create Map", "create-map": "Create Map",
"map-viewer": "Map", "map-viewer": "Map",
"pinned-note": "Pinned note" "pinned-note": "Pinned note",
"item-sheet": "Item"
} }

View File

@@ -62,6 +62,12 @@
"new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.", "new": "Nuevo objeto", "edit": "Editar objeto", "foundry-sync-note": "Los cambios en este objeto también se aplican al mundo de Foundry vinculado.",
"category": "Categoría", "rarity": "Rareza", "quantity": "Cantidad", "category": "Categoría", "rarity": "Rareza", "quantity": "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",
"sheet": {
"icon": "Icono del objeto", "choose-icon": "Elegir tu propio icono", "change-icon": "Cambiar icono",
"uploading": "Subiendo...", "upload-error": "No se pudo subir este icono.",
"foundry-icon": "Usar el icono de Foundry", "remove-icon": "Quitar el icono", "save-error": "No se pudo guardar este objeto.",
"no-description": "Sin descripción añadida."
},
"categories": { "categories": {
"weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura", "weapon": "Arma", "armor": "Armadura", "shield": "Escudo", "adventuring-gear": "Equipo de aventura",
"magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro" "magic-item": "Objeto mágico", "consumable": "Consumible", "tool": "Herramienta", "treasure": "Tesoro", "other": "Otro"

View File

@@ -8,5 +8,6 @@
"create-campaign": "Crear campanya", "create-campaign": "Crear campanya",
"create-map": "Crear mapa", "create-map": "Crear mapa",
"map-viewer": "Mapa", "map-viewer": "Mapa",
"pinned-note": "Nota fijada" "pinned-note": "Nota fijada",
"item-sheet": "Objeto"
} }

View File

@@ -0,0 +1,105 @@
// Tests for Syndria98/dragonroll#35: clicking an item in the campaign sidebar opens a window with
// the item's info, and that window can pick the item's icon — Foundry's own when the item is synced,
// or an uploaded one.
//
// The mapper from a Foundry item to Dragonroll item fields is a pure CommonJS service, so it is
// required and called directly. The window wiring lives in files this repository installs no
// dependencies for, so those checks read the sources, like tests/map-viewer.test.js does.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const { foundryItemToItemData } = require(path.join(__dirname, "..", "backend", "src", "services", "item-foundry"));
const sidebarSource = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
const itemWindowSource = read("frontend", "app", "components", "windows", "ItemSheetWindow.vue");
const itemRouteSource = read("backend", "src", "routes", "item.js");
const itemModelSource = read("backend", "src", "models", "Item.js");
const foundryLinkSource = read("backend", "src", "routes", "foundry-link.js");
const moduleSource = read("dragonroll-foundry", "scripts", "api.js");
test("a synced Foundry item carries its icon over to the Dragonroll item", () => {
const fields = foundryItemToItemData({
name: "Longsword",
type: "weapon",
img: "http://vtt.test/icons/svg/sword.svg",
system: { quantity: 1, weight: 3, rarity: "common" },
});
assert.equal(fields.image, "http://vtt.test/icons/svg/sword.svg");
});
test("a Foundry item without an icon maps to an empty one", () => {
const fields = foundryItemToItemData({ name: "Torch", type: "loot", system: { quantity: 1 } });
assert.equal(fields.image, "");
});
test("the Item model stores the icon and the icon Foundry last sent", () => {
assert.match(itemModelSource, /image:\s*{\s*type:\s*String/);
assert.match(itemModelSource, /foundryImage:\s*{\s*type:\s*String/);
});
test("Foundry sync keeps foundryImage even when the save preserves Dragonroll edits", () => {
// The preserve-edits rule must not cover foundryImage: it is Foundry's state,
// and the item window offers it back after the user picked their own icon.
const keep = /if \(!fullSync \|\| item\.isNew\) Object\.assign\(item, fields\);([\s\S]{0,220}?)if \(!item\.foundryNames/.exec(foundryLinkSource);
assert.ok(keep, "expected the foundryImage keep between the guarded assign and the name bookkeeping");
assert.match(keep[1], /if \(fields\.image\) item\.foundryImage = fields\.image;/);
});
test("the item routes accept the icon and upload one", () => {
assert.match(itemRouteSource, /router\.post\(["']\/upload-image["'], upload\.single\(["']image["']\)/);
assert.match(itemRouteSource, /req\.query\.item \|\| req\.body\.item/);
assert.match(itemRouteSource, /item\.image = req\.file\.filename/);
// the upload checks ownership like every other item handler
const uploadRoute = /router\.post\(["']\/upload-image[\s\S]*?module\.exports/.exec(itemRouteSource)?.[0] ?? itemRouteSource;
assert.match(uploadRoute, /userOwnsCampaign\(item\.campaign, req\.user\.id\)/);
// /update accepts the icon so the window can switch between own and Foundry's
assert.match(itemRouteSource, /if \(image !== undefined\) item\.image = String\(image\);/);
});
test("the item info window is registered and opens on a sidebar click", () => {
assert.match(windowDefsSource, /item_sheet:\s*{\s*title:[^}]*ItemSheetWindow\.vue/s);
// clicking (or Enter/Space on) an item row opens the window instead of expanding inline
assert.match(sidebarSource, /v-for="item in items"[^>]*@click="openItemSheet\(item\)"/);
assert.match(sidebarSource, /CreateWindow\(['"]item_sheet['"],\s*\{ item \}\)/);
assert.doesNotMatch(sidebarSource, /toggleEntryDetails/);
});
test("the item window shows the info and offers both icon sources", () => {
// info: name, category, rarity, quantity, weight, properties, description
for (const key of ["form.name", "form.category", "form.rarity", "form.quantity", "form.weight", "form.properties", "form.description"]) {
assert.ok(itemWindowSource.includes(key), `expected the window to render ${key}`);
}
// own icon: upload through the item route like the character sheet does its photo
assert.match(itemWindowSource, /\/item\/upload-image\?item=/);
// Foundry icon: switch the item image back to the one the world sent
assert.match(itemWindowSource, /form\.value\.foundryImage/);
assert.match(itemWindowSource, /updateItem\(\{ image: form\.value\.foundryImage \}\)/);
// uploads resolve as backend /public files, world URLs load as they are
assert.match(itemWindowSource, /\$\{getBaseUrl\(\)\}\/public\//);
});
test("the Foundry module sends item icons as URLs Dragonroll can load", () => {
// actor-embedded items go through the same serializer as world items
assert.match(moduleSource, /items:\s*\(actor\.items\?\.contents\?\.map\(serializeFoundryItem\)/);
// the icon chosen in Dragonroll travels back into the linked world
assert.match(moduleSource, /const image = getDragonrollImageUrl\(entry\.image\);\s*if \(image\) updates\.img = image;/);
assert.match(moduleSource, /img: getDragonrollImageUrl\(entry\.image\) \|\| undefined,\s*system:/);
});
test("every locale names the item window and its icon controls", () => {
for (const locale of ["en", "es", "ca"]) {
const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json"));
assert.ok(windows["item-sheet"], `${locale} is missing the item window title`);
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
for (const key of ["choose-icon", "change-icon", "foundry-icon", "remove-icon", "upload-error"]) {
assert.ok(campaigns.item?.sheet?.[key], `${locale} is missing campaigns.item.sheet.${key}`);
}
}
});