Image support!
Some checks failed
Test / test (push) Failing after 5s
Build and Deploy Nuxt / build (push) Successful in 1m46s

This commit is contained in:
2026-11-20 19:10:28 +01:00
parent d61659cfdd
commit fe662bb351
11 changed files with 119 additions and 21 deletions

View File

@@ -21,6 +21,26 @@ async function noteFolderFor(folderId, campaignId) {
return Folder.belongsToSection(folderId, campaignId, 'note'); return Folder.belongsToSection(folderId, campaignId, 'note');
} }
// Every media row of a campaign, so a note can link to an upload by name (`[[harbour.png]]`) or
// display it (`![[harbour.png]]`).
router.get('/list', async (req, res) => {
try {
const { campaign } = req.query;
if (!campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const media = await Media.find({ campaign })
.select('_id name file mimeType date')
.sort({ name: 1 })
.lean();
res.json({ status: 'ok', media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/upload', upload.single('file'), async (req, res) => { router.post('/upload', upload.single('file'), async (req, res) => {
try { try {
const { campaign, folder } = req.body; const { campaign, folder } = req.body;

View File

@@ -23,6 +23,8 @@ const loading = ref(true);
const campaignId = computed(() => Campaign.value?._id ?? Campaign.value?.id ?? null); const campaignId = computed(() => Campaign.value?._id ?? Campaign.value?.id ?? null);
const isActor = computed(() => target.value?.type === 'actor'); const isActor = computed(() => target.value?.type === 'actor');
const isItem = computed(() => target.value?.type === 'item'); const isItem = computed(() => target.value?.type === 'item');
const isMedia = computed(() => target.value?.type === 'media');
const isImage = computed(() => String(entry.value?.mimeType ?? '').startsWith('image/'));
onMounted(async () => { onMounted(async () => {
const targets = await LoadLinkTargets(campaignId.value); const targets = await LoadLinkTargets(campaignId.value);
@@ -71,6 +73,7 @@ function resolveImage(image) {
} }
const imageUrl = computed(() => resolveImage(entry.value?.image)); const imageUrl = computed(() => resolveImage(entry.value?.image));
const mediaUrl = computed(() => entry.value?.file ? `${getBaseUrl()}/public/${entry.value.file}` : '');
const initial = computed(() => String(entry.value?.name ?? '?').slice(0, 1).toUpperCase()); const initial = computed(() => String(entry.value?.name ?? '?').slice(0, 1).toUpperCase());
// --- The item's sheet, in the small --- // --- The item's sheet, in the small ---
@@ -137,6 +140,11 @@ async function openSheet() {
</span> </span>
</span> </span>
<span v-else-if="entry && isMedia" class="embedded-media">
<img v-if="isImage" class="embed-image" :src="mediaUrl" :alt="entry.name">
<a v-else class="embed-file" :href="mediaUrl" target="_blank" rel="noopener">{{ entry.name }}</a>
</span>
<span v-else class="embedded-entry embedded-missing" :title="translate('campaigns.link-preview.not-found')">{{ href }}</span> <span v-else class="embedded-entry embedded-missing" :title="translate('campaigns.link-preview.not-found')">{{ href }}</span>
</template> </template>
@@ -226,6 +234,19 @@ async function openSheet() {
.embed-open:hover { background: var(--color-button-hover); } .embed-open:hover { background: var(--color-button-hover); }
/* An embedded upload: an image fills the note's width, any other file is offered as a link. */
.embedded-media { display: inline-block; max-width: 100%; margin: 8px 0; vertical-align: top; }
.embed-image {
display: block;
max-width: 100%;
height: auto;
border: 1px solid var(--color-border);
border-radius: 8px;
}
.embed-file { color: var(--color-link); word-break: break-word; }
.embed-vitals { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; } .embed-vitals { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.embed-stat { .embed-stat {

View File

@@ -126,7 +126,7 @@ function linkEntry(target) {
kind: 'link', kind: 'link',
value: target, value: target,
label: `[[${target.label}]]`, label: `[[${target.label}]]`,
hint: t(`campaigns.sections.${target.type}s`) hint: t(target.type === 'media' ? 'campaigns.sections.media' : `campaigns.sections.${target.type}s`)
}; };
} }
@@ -451,6 +451,12 @@ async function openLinkTarget(target) {
if (target.type === 'map') { if (target.type === 'map') {
const map = await LoadLinkEntry(campaignId.value, 'map', target.id); const map = await LoadLinkEntry(campaignId.value, 'map', target.id);
if (map) AnchorMap(map); if (map) AnchorMap(map);
return;
}
if (target.type === 'media') {
const media = await LoadLinkEntry(campaignId.value, 'media', target.id);
if (media) CreateWindow('media_viewer', { media });
} }
} }

View File

@@ -36,6 +36,12 @@ the way a file explorer does. Clicking a row opens the file in a window of its o
moves into a folder like a note — drag it there, or use **Move to Folder…** in its right-click menu. moves into a folder like a note — drag it there, or use **Move to Folder…** in its right-click menu.
Right-clicking a media row also deletes it, file included. Right-clicking a media row also deletes it, file included.
A note can point at an uploaded file by its name, the same way it links to the rest of the campaign.
Write `![[harbour.png]]` and an image is drawn in the note at that spot — the picture fills the note's
width. A sound, a video or a PDF written this way is shown as a link to the file. Without the **!** the
file's name is a normal link that opens the media window when clicked: `[[harbour.png]]`. Typing `[[`
while editing offers the uploaded files in the same menu as notes, characters, items and maps.
## Markdown ## Markdown
Headings, **bold**, *italic*, lists, quotes, tables, code and links all work: Headings, **bold**, *italic*, lists, quotes, tables, code and links all work:
@@ -78,9 +84,10 @@ species, armour class, hit points, speed and ability scores, with the traits, pr
spells below. An item arrives with its icon, category, rarity, weight, properties and description. spells below. An item arrives with its icon, category, rarity, weight, properties and description.
The embedded card is part of the note in display mode, and its **Open** button opens the full sheet, The embedded card is part of the note in display mode, and its **Open** button opens the full sheet,
the same window the sidebar opens. Only characters and items can be embedded; a note or a map written the same window the sidebar opens. An uploaded image can be embedded the same way (`![[harbour.png]]`,
with the **!** stays as plain text. Name resolution works exactly like a normal link, so an embed of see [Images and media](#images-and-media)). A note or a map written with the **!** stays as plain text.
an entry that has been renamed is shown dimmed. Name resolution works exactly like a normal link, so an embed of an entry that has been renamed is
shown dimmed.
## Rolling dice in a note ## Rolling dice in a note

View File

@@ -1,5 +1,6 @@
// The rules behind the note editor's wiki-link autocomplete (type `[[` while editing a note and the // The rules behind the note editor's wiki-link autocomplete (type `[[` while editing a note and the
// campaign's notes, actors, items and maps are offered to link to). These helpers hold no state, // campaign's notes, actors, items, maps and uploaded files are offered to link to). These helpers
// hold no state,
// touch no DOM and import nothing, so tests can load them straight from source. Marker.js renders // touch no DOM and import nothing, so tests can load them straight from source. Marker.js renders
// `[[target]]` as a link, so the target written here is the entry's label. // `[[target]]` as a link, so the target written here is the entry's label.
@@ -30,10 +31,10 @@ function FindLinkTrigger(text, caret) {
return { start, query }; return { start, query };
} }
// One `{ id, label, type }` per linkable entry, from the campaign's four lists. Entries without a // One `{ id, label, type }` per linkable entry, from the campaign's lists. Entries without a name
// name are left out (they would show as an empty menu row), the rest are sorted by label so the menu // are left out (they would show as an empty menu row), the rest are sorted by label so the menu
// reads alphabetically whatever order the API answered with. // reads alphabetically whatever order the API answered with.
function BuildLinkSuggestions({ notes, actors, items, maps } = {}) { function BuildLinkSuggestions({ notes, actors, items, maps, media } = {}) {
const suggestions = []; const suggestions = [];
const seen = new Set(); const seen = new Set();
@@ -52,6 +53,7 @@ function BuildLinkSuggestions({ notes, actors, items, maps } = {}) {
push('actor', actors, (actor) => actor.name); push('actor', actors, (actor) => actor.name);
push('item', items, (item) => item.name); push('item', items, (item) => item.name);
push('map', maps, (map) => map.name); push('map', maps, (map) => map.name);
push('media', media, (file) => file.name);
return suggestions.sort((a, b) => a.label.localeCompare(b.label)); return suggestions.sort((a, b) => a.label.localeCompare(b.label));
} }

View File

@@ -9,14 +9,15 @@ import { BuildLinkSuggestions } from './LinkAutocomplete';
const CACHE_TTL = 30 * 1000; const CACHE_TTL = 30 * 1000;
const cache = new Map(); // campaignId → { at, promise } const cache = new Map(); // campaignId → { at, promise }
// The campaign's four lists as the API answers them. The note preview needs the entry itself (a // The campaign's lists as the API answers them. The note preview needs the entry itself (a
// character sheet, an item), not only the label the suggestion carries, so the lists are kept as // character sheet, an item), not only the label the suggestion carries, so the lists are kept as
// they arrive and both readers resolve from the same round of requests. // they arrive and both readers resolve from the same round of requests.
const LIST_PATHS = { const LIST_PATHS = {
note: { path: '/note/all', key: 'notes' }, note: { path: '/note/all', key: 'notes' },
actor: { path: '/actor/list', key: 'actors' }, actor: { path: '/actor/list', key: 'actors' },
item: { path: '/item/list', key: 'items' }, item: { path: '/item/list', key: 'items' },
map: { path: '/map/list', key: 'maps' } map: { path: '/map/list', key: 'maps' },
media: { path: '/media/list', key: 'media' }
}; };
async function fetchList(campaignId, path, key) { async function fetchList(campaignId, path, key) {
@@ -32,7 +33,7 @@ async function fetchList(campaignId, path, key) {
function LoadCampaignEntries(campaignId) { function LoadCampaignEntries(campaignId) {
const id = campaignId ? String(campaignId) : ''; const id = campaignId ? String(campaignId) : '';
if (!id) { if (!id) {
return Promise.resolve({ notes: [], actors: [], items: [], maps: [] }); return Promise.resolve({ notes: [], actors: [], items: [], maps: [], media: [] });
} }
const cached = cache.get(id); const cached = cache.get(id);
@@ -40,7 +41,7 @@ function LoadCampaignEntries(campaignId) {
const promise = Promise.all( const promise = Promise.all(
Object.values(LIST_PATHS).map(({ path, key }) => fetchList(id, path, key)) Object.values(LIST_PATHS).map(({ path, key }) => fetchList(id, path, key))
).then(([notes, actors, items, maps]) => ({ notes, actors, items, maps })); ).then(([notes, actors, items, maps, media]) => ({ notes, actors, items, maps, media }));
cache.set(id, { at: Date.now(), promise }); cache.set(id, { at: Date.now(), promise });
return promise; return promise;

View File

@@ -37,7 +37,7 @@
}, },
"sidebar-label": "Campanya", "sidebar-label": "Campanya",
"synced": "Sincronitzat", "synced": "Sincronitzat",
"sections": { "notes": "Notes", "actors": "Actors i personatges", "items": "Objectes", "maps": "Mapes" }, "sections": { "notes": "Notes", "actors": "Actors i personatges", "items": "Objectes", "maps": "Mapes", "media": "Fitxers" },
"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", "edit": "Edita", "save": "Desa", "delete": "Suprimeix", "saving": "Desant...", "create": "Crea {section}", "submit": "Crea", "edit": "Edita", "save": "Desa", "delete": "Suprimeix", "saving": "Desant...",

View File

@@ -41,7 +41,7 @@
}, },
"sidebar-label": "Campaign", "sidebar-label": "Campaign",
"synced": "Synced", "synced": "Synced",
"sections": { "notes": "Notes", "actors": "Actors & Characters", "items": "Items", "maps": "Maps" }, "sections": { "notes": "Notes", "actors": "Actors & Characters", "items": "Items", "maps": "Maps", "media": "Media" },
"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", "edit": "Edit", "save": "Save", "delete": "Delete", "saving": "Saving...", "create": "Create {section}", "submit": "Create", "edit": "Edit", "save": "Save", "delete": "Delete", "saving": "Saving...",

View File

@@ -37,7 +37,7 @@
}, },
"sidebar-label": "Campaña", "sidebar-label": "Campaña",
"synced": "Sincronizado", "synced": "Sincronizado",
"sections": { "notes": "Notas", "actors": "Actores y personajes", "items": "Objetos", "maps": "Mapas" }, "sections": { "notes": "Notas", "actors": "Actores y personajes", "items": "Objetos", "maps": "Mapas", "media": "Archivos" },
"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", "edit": "Editar", "save": "Guardar", "delete": "Eliminar", "saving": "Guardando...", "create": "Crear {section}", "submit": "Crear", "edit": "Editar", "save": "Guardar", "delete": "Eliminar", "saving": "Guardando...",

View File

@@ -61,6 +61,14 @@ test("every named note, actor, item and map becomes a suggestion, sorted by labe
]); ]);
}); });
test("an uploaded file is offered like any other entry, under its name", () => {
const suggestions = autocomplete.BuildLinkSuggestions({
media: [{ _id: "f1", name: "harbour.png" }, { _id: "f2", file: "no-name.png" }],
});
assert.deepEqual(suggestions, [{ id: "f1", label: "harbour.png", type: "media" }]);
});
test("entries without a name are left out, and a repeated label is offered once", () => { test("entries without a name are left out, and a repeated label is offered once", () => {
const suggestions = autocomplete.BuildLinkSuggestions({ const suggestions = autocomplete.BuildLinkSuggestions({
notes: [{ _id: "n1", title: "The Inn" }, { _id: "n2", title: "The Inn" }, { _id: "n3" }], notes: [{ _id: "n1", title: "The Inn" }, { _id: "n2", title: "The Inn" }, { _id: "n3" }],
@@ -133,18 +141,19 @@ function wiringTests() {
assert.match(note, /@select="applySuggestion"/); assert.match(note, /@select="applySuggestion"/);
}); });
test("the entries a note can link to are the campaign's four lists", () => { test("the entries a note can link to are the campaign's lists", () => {
for (const path of ["/note/all", "/actor/list", "/item/list", "/map/list"]) { for (const path of ["/note/all", "/actor/list", "/item/list", "/map/list", "/media/list"]) {
assert.ok(targets.includes(path), `the link entries do not read ${path}`); assert.ok(targets.includes(path), `the link entries do not read ${path}`);
} }
assert.match(targets, /CACHE_TTL/, "the four lists are cached instead of fetched per keystroke"); assert.match(targets, /CACHE_TTL/, "the lists are cached instead of fetched per keystroke");
}); });
test("the link menu names its section in every locale", () => { test("the link menu names its section in every locale", () => {
for (const locale of ["en", "es", "ca"]) { for (const locale of ["en", "es", "ca"]) {
const sections = JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "campaigns.json")).sections; const sections = JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "campaigns.json")).sections;
for (const type of ["note", "actor", "item", "map"]) { for (const type of ["note", "actor", "item", "map", "media"]) {
assert.ok(sections[`${type}s`], `${locale} has no label for the ${type} section`); const key = type === "media" ? "media" : `${type}s`;
assert.ok(sections[key], `${locale} has no label for the ${type} section`);
} }
} }
}); });

View File

@@ -46,7 +46,7 @@ function loadRoutes(file, models) {
}; };
} }
function loadMediaRoutes({ ownsCampaign = true, media = null, folderOk = true } = {}) { function loadMediaRoutes({ ownsCampaign = true, media = null, folderOk = true, list = [] } = {}) {
const deleted = []; const deleted = [];
const api = loadRoutes("media.js", { const api = loadRoutes("media.js", {
"../models/Campaign": { findOne: () => ({ lean: async () => (ownsCampaign ? { _id: "campaign-1" } : null) }) }, "../models/Campaign": { findOne: () => ({ lean: async () => (ownsCampaign ? { _id: "campaign-1" } : null) }) },
@@ -55,6 +55,11 @@ function loadMediaRoutes({ ownsCampaign = true, media = null, folderOk = true }
function Media(data) { Object.assign(this, { _id: "media-new", save: async () => {} }, data); }, function Media(data) { Object.assign(this, { _id: "media-new", save: async () => {} }, data); },
{ {
findById: async () => media, findById: async () => media,
find: (filter) => ({
select() { return this; },
sort() { return this; },
lean: async () => (filter.campaign === "campaign-1" ? list : []),
}),
deleteOne: async (filter) => { deleted.push(filter); return { deletedCount: 1 }; }, deleteOne: async (filter) => { deleted.push(filter); return { deletedCount: 1 }; },
} }
), ),
@@ -95,6 +100,22 @@ test("an upload into another campaign is refused", async () => {
assert.equal(response.msg, "unauthorized"); assert.equal(response.msg, "unauthorized");
}); });
test("a campaign's media can be listed so a note can link to it", async () => {
const list = [{ _id: "media-1", name: "harbour.png", file: "file-1.png", mimeType: "image/png" }];
const { api } = loadMediaRoutes({ list });
const response = await api("GET /list", { query: { campaign: "campaign-1" } });
assert.equal(response.status, "ok");
assert.deepEqual(response.media, list);
});
test("the media list of another campaign is refused", async () => {
const { api } = loadMediaRoutes({ ownsCampaign: false });
const response = await api("GET /list", { query: { campaign: "campaign-1" } });
assert.equal(response.msg, "unauthorized");
});
test("a media file only stands in a note folder", async () => { test("a media file only stands in a note folder", async () => {
const { api } = loadMediaRoutes({ folderOk: false }); const { api } = loadMediaRoutes({ folderOk: false });
const response = await api("POST /upload", { const response = await api("POST /upload", {
@@ -187,6 +208,17 @@ test("a media window is registered and reads the file from /api/public", () => {
assert.match(viewer, /getBaseUrl\(\)\}\/public\/\$\{media\.file\}/); assert.match(viewer, /getBaseUrl\(\)\}\/public\/\$\{media\.file\}/);
}); });
test("an embedded image from the media list is drawn in the note", () => {
const embed = read("frontend", "app", "components", "viewer", "content", "EmbeddedEntry.vue");
assert.match(embed, /target\.value\?\.type === 'media'/, "media becomes an embed target");
assert.match(embed, /startsWith\('image\/'\)/, "only an image is drawn as a picture");
assert.match(embed, /getBaseUrl\(\)\}\/public\/\$\{entry\.value\.file\}/, "the upload is served from /api/public");
assert.match(embed, /class="embed-image"/);
const note = read("frontend", "app", "components", "viewer", "content", "Note.vue");
assert.match(note, /CreateWindow\('media_viewer'/, "a plain link to a media file opens its window");
});
test("every locale names the upload and the media window", () => { test("every locale names the upload and the media window", () => {
for (const locale of ["en", "es", "ca"]) { for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json")); const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));