From fe662bb351caee3879598b97860aada09b21f758 Mon Sep 17 00:00:00 2001 From: Aran Roig Date: Fri, 20 Nov 2026 19:10:28 +0100 Subject: [PATCH] Image support! --- backend/src/routes/media.js | 20 +++++++++++ .../viewer/content/EmbeddedEntry.vue | 21 ++++++++++++ .../app/components/viewer/content/Note.vue | 8 ++++- .../01-notes-and-markdown.md | 13 +++++-- frontend/app/services/LinkAutocomplete.js | 10 +++--- frontend/app/services/LinkTargets.js | 9 ++--- frontend/i18n/locales/ca/campaigns.json | 2 +- frontend/i18n/locales/en/campaigns.json | 2 +- frontend/i18n/locales/es/campaigns.json | 2 +- tests/link-autocomplete.test.js | 19 ++++++++--- tests/note-media.test.js | 34 ++++++++++++++++++- 11 files changed, 119 insertions(+), 21 deletions(-) diff --git a/backend/src/routes/media.js b/backend/src/routes/media.js index 015cb79d..eb6c9112 100644 --- a/backend/src/routes/media.js +++ b/backend/src/routes/media.js @@ -21,6 +21,26 @@ async function noteFolderFor(folderId, campaignId) { 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) => { try { const { campaign, folder } = req.body; diff --git a/frontend/app/components/viewer/content/EmbeddedEntry.vue b/frontend/app/components/viewer/content/EmbeddedEntry.vue index d431974d..3d9fac0d 100644 --- a/frontend/app/components/viewer/content/EmbeddedEntry.vue +++ b/frontend/app/components/viewer/content/EmbeddedEntry.vue @@ -23,6 +23,8 @@ const loading = ref(true); const campaignId = computed(() => Campaign.value?._id ?? Campaign.value?.id ?? null); const isActor = computed(() => target.value?.type === 'actor'); 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 () => { const targets = await LoadLinkTargets(campaignId.value); @@ -71,6 +73,7 @@ function resolveImage(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()); // --- The item's sheet, in the small --- @@ -137,6 +140,11 @@ async function openSheet() { + + + {{ entry.name }} + + {{ href }} @@ -226,6 +234,19 @@ async function openSheet() { .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-stat { diff --git a/frontend/app/components/viewer/content/Note.vue b/frontend/app/components/viewer/content/Note.vue index 9da8ac55..07ca5dd8 100644 --- a/frontend/app/components/viewer/content/Note.vue +++ b/frontend/app/components/viewer/content/Note.vue @@ -126,7 +126,7 @@ function linkEntry(target) { kind: 'link', value: target, 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') { const map = await LoadLinkEntry(campaignId.value, 'map', target.id); if (map) AnchorMap(map); + return; + } + + if (target.type === 'media') { + const media = await LoadLinkEntry(campaignId.value, 'media', target.id); + if (media) CreateWindow('media_viewer', { media }); } } diff --git a/frontend/app/content/docs/02-using-dragonroll/01-notes-and-markdown.md b/frontend/app/content/docs/02-using-dragonroll/01-notes-and-markdown.md index 6230d7df..74a63801 100644 --- a/frontend/app/content/docs/02-using-dragonroll/01-notes-and-markdown.md +++ b/frontend/app/content/docs/02-using-dragonroll/01-notes-and-markdown.md @@ -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. 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 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. 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 -with the **!** stays as plain text. Name resolution works exactly like a normal link, so an embed of -an entry that has been renamed is shown dimmed. +the same window the sidebar opens. An uploaded image can be embedded the same way (`![[harbour.png]]`, +see [Images and media](#images-and-media)). A note or a map written with the **!** stays as plain text. +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 diff --git a/frontend/app/services/LinkAutocomplete.js b/frontend/app/services/LinkAutocomplete.js index 1e7b450c..04133bde 100644 --- a/frontend/app/services/LinkAutocomplete.js +++ b/frontend/app/services/LinkAutocomplete.js @@ -1,5 +1,6 @@ // 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 // `[[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 }; } -// One `{ id, label, type }` per linkable entry, from the campaign's four lists. Entries without a -// name are left out (they would show as an empty menu row), the rest are sorted by label so the menu +// One `{ id, label, type }` per linkable entry, from the campaign's lists. Entries without a name +// 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. -function BuildLinkSuggestions({ notes, actors, items, maps } = {}) { +function BuildLinkSuggestions({ notes, actors, items, maps, media } = {}) { const suggestions = []; const seen = new Set(); @@ -52,6 +53,7 @@ function BuildLinkSuggestions({ notes, actors, items, maps } = {}) { push('actor', actors, (actor) => actor.name); push('item', items, (item) => item.name); push('map', maps, (map) => map.name); + push('media', media, (file) => file.name); return suggestions.sort((a, b) => a.label.localeCompare(b.label)); } diff --git a/frontend/app/services/LinkTargets.js b/frontend/app/services/LinkTargets.js index 747177af..5df5259a 100644 --- a/frontend/app/services/LinkTargets.js +++ b/frontend/app/services/LinkTargets.js @@ -9,14 +9,15 @@ import { BuildLinkSuggestions } from './LinkAutocomplete'; const CACHE_TTL = 30 * 1000; 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 // they arrive and both readers resolve from the same round of requests. const LIST_PATHS = { note: { path: '/note/all', key: 'notes' }, actor: { path: '/actor/list', key: 'actors' }, 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) { @@ -32,7 +33,7 @@ async function fetchList(campaignId, path, key) { function LoadCampaignEntries(campaignId) { const id = campaignId ? String(campaignId) : ''; if (!id) { - return Promise.resolve({ notes: [], actors: [], items: [], maps: [] }); + return Promise.resolve({ notes: [], actors: [], items: [], maps: [], media: [] }); } const cached = cache.get(id); @@ -40,7 +41,7 @@ function LoadCampaignEntries(campaignId) { const promise = Promise.all( 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 }); return promise; diff --git a/frontend/i18n/locales/ca/campaigns.json b/frontend/i18n/locales/ca/campaigns.json index 1c4147ad..ab7a6ac3 100644 --- a/frontend/i18n/locales/ca/campaigns.json +++ b/frontend/i18n/locales/ca/campaigns.json @@ -37,7 +37,7 @@ }, "sidebar-label": "Campanya", "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": { "new-note": "Nota nova", "new-folder": "Carpeta nova", "refresh": "Actualitza", "create": "Crea {section}", "submit": "Crea", "edit": "Edita", "save": "Desa", "delete": "Suprimeix", "saving": "Desant...", diff --git a/frontend/i18n/locales/en/campaigns.json b/frontend/i18n/locales/en/campaigns.json index b52d200a..999c2337 100644 --- a/frontend/i18n/locales/en/campaigns.json +++ b/frontend/i18n/locales/en/campaigns.json @@ -41,7 +41,7 @@ }, "sidebar-label": "Campaign", "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": { "new-note": "New note", "new-folder": "New folder", "refresh": "Refresh", "create": "Create {section}", "submit": "Create", "edit": "Edit", "save": "Save", "delete": "Delete", "saving": "Saving...", diff --git a/frontend/i18n/locales/es/campaigns.json b/frontend/i18n/locales/es/campaigns.json index eb51e41a..047805be 100644 --- a/frontend/i18n/locales/es/campaigns.json +++ b/frontend/i18n/locales/es/campaigns.json @@ -37,7 +37,7 @@ }, "sidebar-label": "Campaña", "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": { "new-note": "Nueva nota", "new-folder": "Nueva carpeta", "refresh": "Actualizar", "create": "Crear {section}", "submit": "Crear", "edit": "Editar", "save": "Guardar", "delete": "Eliminar", "saving": "Guardando...", diff --git a/tests/link-autocomplete.test.js b/tests/link-autocomplete.test.js index 7d1cbe2c..87ffe566 100644 --- a/tests/link-autocomplete.test.js +++ b/tests/link-autocomplete.test.js @@ -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", () => { const suggestions = autocomplete.BuildLinkSuggestions({ notes: [{ _id: "n1", title: "The Inn" }, { _id: "n2", title: "The Inn" }, { _id: "n3" }], @@ -133,18 +141,19 @@ function wiringTests() { assert.match(note, /@select="applySuggestion"/); }); - test("the entries a note can link to are the campaign's four lists", () => { - for (const path of ["/note/all", "/actor/list", "/item/list", "/map/list"]) { + 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", "/media/list"]) { 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", () => { for (const locale of ["en", "es", "ca"]) { const sections = JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "campaigns.json")).sections; - for (const type of ["note", "actor", "item", "map"]) { - assert.ok(sections[`${type}s`], `${locale} has no label for the ${type} section`); + for (const type of ["note", "actor", "item", "map", "media"]) { + const key = type === "media" ? "media" : `${type}s`; + assert.ok(sections[key], `${locale} has no label for the ${type} section`); } } }); diff --git a/tests/note-media.test.js b/tests/note-media.test.js index 7a568845..c0ce25ae 100644 --- a/tests/note-media.test.js +++ b/tests/note-media.test.js @@ -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 api = loadRoutes("media.js", { "../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); }, { 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 }; }, } ), @@ -95,6 +100,22 @@ test("an upload into another campaign is refused", async () => { 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 () => { const { api } = loadMediaRoutes({ folderOk: false }); 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\}/); }); +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", () => { for (const locale of ["en", "es", "ca"]) { const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));