diff --git a/AGENTS.md b/AGENTS.md index 8927aa4e..f4f82f5b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -161,7 +161,7 @@ User ──< Campaign ──< Note ──?> Folder ──?> Folder (parentFolder | `Folder` | `models/Folder.js` | `name*`, `campaign*` → Campaign, `parentFolder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` | | `Actor` | `models/Actor.js` | `name*`, `type` (`character`\|`npc`\|`creature`), `species`, `className`, `subclass`, `level`, `background`, `challengeRating`, `description`, `image`, `abilityScores{str..cha}`, `armorClass`, `speed`, `proficiencies`, `inventory[{name,quantity,weight}]` (flattened Foundry items, embedded — not `Item` docs), `traits`, `spells` (newline text), `campaign*` → Campaign, `foundryActorId` (unique per campaign), `date` | | `Item` | `models/Item.js` | `name*`, `category` (`weapon`\|`armor`\|`shield`\|`adventuring-gear`\|`magic-item`\|`consumable`\|`tool`\|`treasure`\|`other`), `rarity` (`common`…`artifact`), `quantity`, `weight`, `properties`, `description`, `campaign*` → Campaign, `foundryItemId` (unique per campaign), `foundryNames` (names Foundry uses for it, keeps dedup stable across a Dragonroll rename), `date` | -| `Map` | `models/Map.js` | `name*`, `image` (filename in `src/uploads`), `gridSize` (cell size in image px), `offsetX`/`offsetY` (grid origin in image px), `scale` (distance one cell stands for), `campaign*` → Campaign, `date` | +| `Map` | `models/Map.js` | `name*`, `image` (filename in `src/uploads`), `gridSize` (cell size in image px), `offsetX`/`offsetY` (grid origin in image px), `scale` (distance one cell stands for), `pins[{note → Note, x, y}]` (a note pinned at image px coordinates, addressed by its own `_id`), `campaign*` → Campaign, `date` | `*` = required. Notes and folders are ordered by `date: -1` everywhere. @@ -195,9 +195,12 @@ Fetch the file from `/api/public/`. `GET /api/note/list?campaign=` → `{status:'ok', folders, notes}` — notes with `folder: null` (roots); folder entries include `parentFolder` so clients can rebuild nested folder paths `GET /api/note/subfolder/list?campaign=&folder=` → `{status:'ok', subfolders, notes}` +`GET /api/note/all?campaign=` → `{status:'ok', notes, folders}` — every note of the campaign, titles +only (no `content`); the map viewer's note picker and its pin labels +`GET /api/note/retrieve/:id` → `{status:'ok',note}` — one note with its content, ownership checked `POST /api/note/create` — `{title*,content,campaign*,folder?}` (folder validated against campaign) `POST /api/note/update` — `{id*, title?, content?, folder?, color?}` — partial, ownership checked -`POST /api/note/delete` — `{id}` — **no ownership check** (§9) +`POST /api/note/delete` — `{id}` — **no ownership check** (§9); pulls the note off every map's `pins` `GET /api/folder/list?campaign=` → `{status:'ok',folders}` `POST /api/folder/create` — `{name*,campaign*}` @@ -224,6 +227,9 @@ subfolders re-parented to null then deleted. `POST /api/map/update` — `{id*, name?, gridSize?, offsetX?, offsetY?, scale?}`, partial, ownership checked. Send it as multipart with an `image` field to replace the photo (multer reads the other fields from the form; JSON works too). `POST /api/map/delete` — `{id}` +`POST /api/map/pin` — `{id*, note*, x, y}` — pins a note of the same campaign at those image px; +pinning a note that is pinned already moves that marker → `{status:'ok',map}` +`POST /api/map/unpin` — `{id*, pin*}` (`pin` is the subdocument `_id`) → `{status:'ok',map}` ### 4.1 Foundry integration (actors, items) @@ -311,7 +317,10 @@ There is no `app/pages/`. `app/app.vue` renders a fixed shell of managers. "Scre shown when `Campaign` state is non-null. The note column shows the open notes, or the map anchored on it (`AnchorMap` / `ActivePane` in `services/Content.js`); the sidebar's notes and maps buttons switch between the two while both keep their state, and `viewer/map/MapViewerPane.vue` renders the - map there and inside the `map_viewer` window (a detached anchored map). + map there and inside the `map_viewer` window (a detached anchored map). Right clicking that map pins + one of the campaign notes at the spot (`services/MapPins.js` translates between image pixels and + the screen and labels the note picker); clicking the marker opens `pinned_note` + (`PinnedNoteWindow.vue`), which reads the note itself through `/note/retrieve/:id`. Boot sequence (`app.vue` → `start()`): @@ -430,8 +439,8 @@ Every listener in the app (there are only these six `emitter.on` call sites): | `toast` | `{color,text,duration}` | `ToastManager.vue` | | `push-note` | `{key,title,text,date}` | `NoteContainer.vue` | | `close-note` | note key (string) | `NoteContainer.vue` (removes the note from the open column only) | -| `delete-note` | note key (string) | `NoteContainer.vue`, `ContentSidebar.vue`, `NestedNoteList.vue` (real deletion: closes the note **and** removes it from the sidebar) | -| `title-updated` | `{key,title}` | `Note.vue`, `NoteContainer.vue` | +| `delete-note` | note key (string) | `NoteContainer.vue`, `ContentSidebar.vue`, `NestedNoteList.vue` (real deletion: closes the note **and** removes it from the sidebar), `MapViewerPane.vue` (drops the markers pinned to that note) | +| `title-updated` | `{key,title}` | `Note.vue`, `NoteContainer.vue`, `MapViewerPane.vue` (relabels the map pins of that note) | | `status-bar-update` | `{text,icon}` | `FetchStatus.vue` | Emitters: `Toaster.js` (`toast`), `ContentSidebar` / `TopSearchBar` (`push-note`), `Note.vue` diff --git a/backend/src/index.js b/backend/src/index.js index 9e1c103a..d04b1e3e 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -62,7 +62,7 @@ const appCors = cors({ credentials: true, // if using cookies/auth }); app.use((req, res, next) => { - if (foundryCorsPaths.some((path) => req.path === path || req.path.startsWith(`${path}/`))) return next(); + if (openCorsPaths.some((path) => req.path === path || req.path.startsWith(`${path}/`))) return next(); appCors(req, res, next); }); diff --git a/backend/src/models/Map.js b/backend/src/models/Map.js index 2f55492a..e9176db5 100644 --- a/backend/src/models/Map.js +++ b/backend/src/models/Map.js @@ -12,6 +12,13 @@ const MapSchema = new Schema({ offsetY: { type: Number, default: 0 }, // Distance each grid cell stands for (feet, metres...) scale: { type: Number, min: 0.01, default: 5 }, + // Notes pinned onto the map like markers. x/y are image pixels from the top left corner of the + // image, so a pin keeps its place whatever the zoom or the grid settings are. + pins: [{ + note: { type: Schema.Types.ObjectId, ref: 'Note', required: true }, + x: { type: Number, default: 0 }, + y: { type: Number, default: 0 } + }], campaign: { type: Schema.Types.ObjectId, ref: 'Campaign', diff --git a/backend/src/routes/map.js b/backend/src/routes/map.js index 659a6500..0d391db3 100644 --- a/backend/src/routes/map.js +++ b/backend/src/routes/map.js @@ -5,6 +5,7 @@ const upload = require('../services/storage'); const Campaign = require('../models/Campaign'); const Map = require('../models/Map'); +const Note = require('../models/Note'); async function userOwnsCampaign(campaignId, userId) { const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); @@ -92,4 +93,63 @@ router.post('/delete', async (req, res) => { } }); +// A pin is a note placed at a spot of the map, in image pixels. Coordinates arrive as strings with +// multipart requests and are never negative: the viewer clamps them to the image already. +function toCoordinate(value) { + const number = Number(value); + if (!Number.isFinite(number)) return 0; + return Math.max(0, Math.round(number)); +} + +router.post('/pin', async (req, res) => { + try { + const { id, note, x, y } = req.body; + if (!id || !note) return res.json({ status: 'error', msg: 'errors.missing-data' }); + + const map = await Map.findById(id); + if (!map) return res.json({ status: 'error', msg: 'errors.notfound' }); + if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' }); + + // Only a note of the same campaign can be pinned onto one of its maps. + const noteDoc = await Note.findOne({ _id: note, campaign: map.campaign }).select('_id').lean(); + if (!noteDoc) return res.json({ status: 'error', msg: 'errors.notfound' }); + + // A note is pinned once per map: pinning it again moves the marker instead of adding a twin. + const pin = map.pins.find((current) => String(current.note) === String(note)); + if (pin) { + pin.x = toCoordinate(x); + pin.y = toCoordinate(y); + } else { + map.pins.push({ note, x: toCoordinate(x), y: toCoordinate(y) }); + } + + await map.save(); + res.json({ status: 'ok', map }); + } catch (err) { + console.error(err); + res.json({ status: 'error', msg: 'errors.internal' }); + } +}); + +router.post('/unpin', async (req, res) => { + try { + const { id, pin } = req.body; + if (!id || !pin) return res.json({ status: 'error', msg: 'errors.missing-data' }); + + const map = await Map.findById(id); + if (!map) return res.json({ status: 'error', msg: 'errors.notfound' }); + if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' }); + + // `_id` stays with the pins that remain: the viewer removes them by that id. + map.pins = map.pins + .filter((current) => String(current._id) !== String(pin)) + .map((current) => ({ _id: current._id, note: current.note, x: current.x, y: current.y })); + await map.save(); + res.json({ status: 'ok', map }); + } catch (err) { + console.error(err); + res.json({ status: 'error', msg: 'errors.internal' }); + } +}); + module.exports = router; diff --git a/backend/src/routes/note.js b/backend/src/routes/note.js index 8d11792e..8773bc47 100644 --- a/backend/src/routes/note.js +++ b/backend/src/routes/note.js @@ -4,6 +4,7 @@ const router = express.Router(); const Campaign = require('../models/Campaign'); const Note = require('../models/Note'); const Folder = require('../models/Folder'); +const Map = require('../models/Map'); async function userOwnsCampaign(campaignId, userId) { const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); @@ -64,6 +65,49 @@ router.get('/subfolder/list', async (req, res) => { } }); +// Every note of the campaign, folders included, without their content: enough to offer a note +// picker and to label the pins other screens put on a map. +router.get('/all', async (req, res) => { + try { + const { campaign } = req.query; + if (!campaign) return res.json({ status: 'error', msg: 'errors.missing-data' }); + + const hasAccess = await userOwnsCampaign(campaign, req.user.id); + if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' }); + + const notes = await Note.find({ campaign }) + .select('_id title folder date') + .sort({ title: 1 }) + .lean(); + + const folders = await Folder.find({ campaign }) + .select('_id name parentFolder') + .lean(); + + res.json({ status: 'ok', notes, folders }); + } catch (err) { + console.error(err); + res.json({ status: 'error', msg: 'errors.internal' }); + } +}); + +// One note with its content, for the screens that show a note on their own (a map pin, for +// instance) instead of from the sidebar's note list. +router.get('/retrieve/:id', async (req, res) => { + try { + const note = await Note.findById(req.params.id).lean(); + if (!note) return res.json({ status: 'error', msg: 'errors.notfound' }); + + const hasAccess = await userOwnsCampaign(note.campaign, req.user.id); + if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' }); + + res.json({ status: 'ok', note }); + } catch (err) { + console.error(err); + res.json({ status: 'error', msg: 'errors.internal' }); + } +}); + router.post('/create', async (req, res) => { try { const { title, content, campaign, folder } = req.body; @@ -119,6 +163,9 @@ router.post('/delete', async (req, res) => { const result = await Note.deleteOne({ _id: id }); if (result.deletedCount === 0) return res.json({ status: 'error', msg: 'errors.notfound' }); + // A pin pointing at a note that is gone would open nothing: drop those along with the note. + await Map.updateMany({ 'pins.note': id }, { $pull: { pins: { note: id } } }); + res.json({ status: 'ok' }); } catch (err) { console.error(err); diff --git a/frontend/app/components/partials/ContentSidebar.vue b/frontend/app/components/partials/ContentSidebar.vue index a6315775..6cf124b1 100644 --- a/frontend/app/components/partials/ContentSidebar.vue +++ b/frontend/app/components/partials/ContentSidebar.vue @@ -120,6 +120,9 @@ function handleCampaignEntryUpdated({ entityType, entry }) { if (!list) return; list.value = list.value.map((current) => current._id === entry._id ? entry : current) .sort((a, b) => a.name.localeCompare(b.name)); + // The anchored map is this very entry (its pins changed, say): write it back without touching + // the pane, so switching back from the notes still shows what is on the map. + if (entityType === 'map' && AnchoredMap.value?._id === entry._id) AnchoredMap.value = entry; } const campaignId = computed(() => { diff --git a/frontend/app/components/viewer/map/MapViewerPane.vue b/frontend/app/components/viewer/map/MapViewerPane.vue index f18cea8c..d6ebf6b6 100644 --- a/frontend/app/components/viewer/map/MapViewerPane.vue +++ b/frontend/app/components/viewer/map/MapViewerPane.vue @@ -1,7 +1,11 @@ @@ -198,10 +341,28 @@ onBeforeUnmount(() => { @pointermove="onPointerMove" @pointerup="onPointerUp" @pointercancel="onPointerUp" + @contextmenu.prevent="onMapContextMenu" >
{{ $t('campaigns.map.no-image') }} @@ -227,6 +388,22 @@ onBeforeUnmount(() => { .map-viewport.dragging { cursor: grabbing; } .map-image { position: absolute; top: 0; left: 0; max-width: none; transform-origin: top left; user-select: none; } .map-grid { position: absolute; top: 0; left: 0; opacity: .55; pointer-events: none; } +/* Pins live in image pixels but are drawn in screen space (see ToScreenPoint), so the overlay stays + unscaled and their markers are readable at every zoom. Only the markers catch the mouse. */ +.map-pins { position: absolute; inset: 0; pointer-events: none; } +.map-pin { + position: absolute; transform: translate(-50%, -100%); pointer-events: auto; + display: flex; align-items: center; gap: 4px; margin: 0; padding: 3px 6px; + border: 1px solid var(--color-link); border-radius: 7px; + background: var(--color-background-soft); color: var(--color-text); + font-size: 11px; cursor: pointer; box-shadow: 0px 0px 6px -1px rgba(0,0,0,0.55); +} +.map-pin:hover { background: var(--color-button-hover); } +.map-pin:focus-visible { outline: 1px solid var(--color-link); } +.pin-icon { width: 12px; height: 12px; filter: invert(var(--color-icon-invert)); } +/* The note's name only when it is asked for: a map full of labels is a map nobody can read. */ +.pin-label { display: none; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.map-pin:hover .pin-label, .map-pin:focus-visible .pin-label { display: inline; } .map-empty { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; font-size: 13px; opacity: .8; } .map-edit { border: 1px solid var(--color-border); border-radius: 7px; padding: 6px 11px; background: var(--color-background-soft); color: var(--color-text); font-size: 12px; cursor: pointer; } .map-edit:hover { background: var(--color-button-hover); } diff --git a/frontend/app/components/windows/PinnedNoteWindow.vue b/frontend/app/components/windows/PinnedNoteWindow.vue new file mode 100644 index 00000000..2414666b --- /dev/null +++ b/frontend/app/components/windows/PinnedNoteWindow.vue @@ -0,0 +1,122 @@ + + + + + diff --git a/frontend/app/services/MapPins.js b/frontend/app/services/MapPins.js new file mode 100644 index 00000000..de9fc308 --- /dev/null +++ b/frontend/app/services/MapPins.js @@ -0,0 +1,77 @@ +// The rules behind the note pins of a map (right click a map, pin one of the campaign notes at that +// spot, click the pin to read it). Pins are stored in image pixels, so these helpers only translate +// between the image and what the map viewer shows; they hold no state and talk to no API. + +const PATH_SEPARATOR = ' / '; + +// Screen pixels (relative to the top left corner of the map viewport) → image pixels, or null when +// the point is not over the image: nothing gets pinned outside of it. +function ToImagePoint(point, view) { + const zoom = Number(view?.zoom); + const width = Number(view?.width); + const height = Number(view?.height); + if (!zoom || !width || !height) return null; + + const x = (Number(point?.x) - Number(view?.pan?.x ?? 0)) / zoom; + const y = (Number(point?.y) - Number(view?.pan?.y ?? 0)) / zoom; + if (!Number.isFinite(x) || !Number.isFinite(y)) return null; + if (x < 0 || y < 0 || x > width || y > height) return null; + + return { x: Math.round(x), y: Math.round(y) }; +} + +// A pin (image pixels) → screen pixels of the map viewport. Pins are drawn in screen space instead +// of inside the scaled stage, so their marker keeps the same size whatever the zoom is. +function ToScreenPoint(pin, view) { + const zoom = Number(view?.zoom) || 0; + return { + x: Number(view?.pan?.x ?? 0) + Number(pin?.x ?? 0) * zoom, + y: Number(view?.pan?.y ?? 0) + Number(pin?.y ?? 0) * zoom + }; +} + +// The path of the folder a note lives in, so two notes sharing a name can still be told apart. +function FolderPath(folderId, folderById) { + const names = []; + const seen = new Set(); + let folder = folderId ? folderById.get(String(folderId)) : null; + // Folder trees are acyclic by construction; `seen` only keeps a broken parent chain from + // looping forever. + while (folder && !seen.has(String(folder._id))) { + seen.add(String(folder._id)); + if (folder.name) names.unshift(String(folder.name)); + folder = folder.parentFolder ? folderById.get(String(folder.parentFolder)) : null; + } + return names.join(PATH_SEPARATOR); +} + +// 'Folder / Subfolder / Note title' out of the picker option's folder path and title. +function OptionLabel(option) { + const path = option?.path ? `${option.path}${PATH_SEPARATOR}` : ''; + return `${path}${option?.title ?? ''}`; +} + +// The note picker of a campaign: `{ value, title, path, label }` per note, sorted by label. Notes +// without a title are left out, they would show as an empty menu entry. +function BuildNoteOptions(notes, folders) { + const folderById = new Map((folders ?? []).map((folder) => [String(folder._id), folder])); + + return (notes ?? []) + .filter((note) => note?._id && String(note.title ?? '').trim()) + .map((note) => { + const option = { + value: String(note._id), + title: String(note.title).trim(), + path: FolderPath(note.folder, folderById) + }; + return { ...option, label: OptionLabel(option) }; + }) + .sort((a, b) => a.label.localeCompare(b.label)); +} + +export { + BuildNoteOptions, + OptionLabel, + ToImagePoint, + ToScreenPoint +}; diff --git a/frontend/app/services/WindowDefinitions.js b/frontend/app/services/WindowDefinitions.js index 75b7ca2c..4529fba6 100644 --- a/frontend/app/services/WindowDefinitions.js +++ b/frontend/app/services/WindowDefinitions.js @@ -82,6 +82,12 @@ const defWindows = { component: () => import('~/components/windows/MapViewerWindow.vue'), close: () => ClearWindow({type: 'map_viewer'}), movable: true + }, + pinned_note: { + title: 'windows.pinned-note', + component: () => import('~/components/windows/PinnedNoteWindow.vue'), + close: () => ClearWindow({type: 'pinned_note'}), + movable: true } } diff --git a/frontend/i18n/locales/ca/campaigns.json b/frontend/i18n/locales/ca/campaigns.json index 341d7889..b85ca8b2 100644 --- a/frontend/i18n/locales/ca/campaigns.json +++ b/frontend/i18n/locales/ca/campaigns.json @@ -78,7 +78,13 @@ "save-error": "No s'ha pogut desar aquest mapa.", "no-image": "Aquest mapa encara no té imatge.", "zoom-in": "Apropar", "zoom-out": "Allunyar", "fit": "Ajustar a la finestra", "toggle-grid": "Mostrar la quadrícula", - "open-window": "Obre en una finestra", "anchored": "Ancorat" + "open-window": "Obre en una finestra", "anchored": "Ancorat", + "pins": { + "add": "Fixa una nota aquí", "none": "Encara no hi ha notes per fixar", + "open": "Obre la nota", "remove": "Treu el marcador", + "error": "No s'han pogut canviar els marcadors d'aquest mapa.", + "note-error": "No s'ha pogut llegir aquesta nota. Potser s'ha suprimit." + } }, "character-sheet": { "title": "Fitxa de personatge", "name": "Nom del personatge", "class": "Classe", "subclass": "Subclasse", "unset-class": "Classe sense definir", diff --git a/frontend/i18n/locales/ca/windows.json b/frontend/i18n/locales/ca/windows.json index 6d5597d5..1678f8c1 100644 --- a/frontend/i18n/locales/ca/windows.json +++ b/frontend/i18n/locales/ca/windows.json @@ -7,5 +7,6 @@ "settings": "Configuració", "create-campaign": "Crear campanya", "create-map": "Crear mapa", - "map-viewer": "Mapa" + "map-viewer": "Mapa", + "pinned-note": "Nota fixada" } diff --git a/frontend/i18n/locales/en/campaigns.json b/frontend/i18n/locales/en/campaigns.json index 8c507ee1..e04a357f 100644 --- a/frontend/i18n/locales/en/campaigns.json +++ b/frontend/i18n/locales/en/campaigns.json @@ -82,7 +82,13 @@ "save-error": "Unable to save this map.", "no-image": "This map has no image yet.", "zoom-in": "Zoom in", "zoom-out": "Zoom out", "fit": "Fit to window", "toggle-grid": "Show grid", - "open-window": "Open in window", "anchored": "Anchored" + "open-window": "Open in window", "anchored": "Anchored", + "pins": { + "add": "Pin a note here", "none": "No notes to pin yet", + "open": "Open note", "remove": "Remove pin", + "error": "Unable to change the pins of this map.", + "note-error": "This note could not be read. It may have been deleted." + } }, "character-sheet": { "title": "Character Sheet", "name": "Character name", "class": "Class", "subclass": "Subclass", "unset-class": "Class not set", diff --git a/frontend/i18n/locales/en/windows.json b/frontend/i18n/locales/en/windows.json index 8d491651..5efefaae 100644 --- a/frontend/i18n/locales/en/windows.json +++ b/frontend/i18n/locales/en/windows.json @@ -7,5 +7,6 @@ "settings": "Settings", "create-campaign": "Create Campaign", "create-map": "Create Map", - "map-viewer": "Map" + "map-viewer": "Map", + "pinned-note": "Pinned note" } diff --git a/frontend/i18n/locales/es/campaigns.json b/frontend/i18n/locales/es/campaigns.json index 6f37731e..89f97f94 100644 --- a/frontend/i18n/locales/es/campaigns.json +++ b/frontend/i18n/locales/es/campaigns.json @@ -78,7 +78,13 @@ "save-error": "No se pudo guardar este mapa.", "no-image": "Este mapa aún no tiene imagen.", "zoom-in": "Acercar", "zoom-out": "Alejar", "fit": "Ajustar a la ventana", "toggle-grid": "Mostrar cuadrícula", - "open-window": "Abrir en una ventana", "anchored": "Anclado" + "open-window": "Abrir en una ventana", "anchored": "Anclado", + "pins": { + "add": "Fija una nota aquí", "none": "Aún no hay notas que fijar", + "open": "Abrir nota", "remove": "Quitar el marcador", + "error": "No se pudieron cambiar los marcadores de este mapa.", + "note-error": "No se pudo leer esta nota. Puede que se haya eliminado." + } }, "character-sheet": { "title": "Hoja de personaje", "name": "Nombre del personaje", "class": "Clase", "subclass": "Subclase", "unset-class": "Clase sin definir", diff --git a/frontend/i18n/locales/es/windows.json b/frontend/i18n/locales/es/windows.json index efb8e85a..c5d46d81 100644 --- a/frontend/i18n/locales/es/windows.json +++ b/frontend/i18n/locales/es/windows.json @@ -7,5 +7,6 @@ "settings": "Configuración", "create-campaign": "Crear campanya", "create-map": "Crear mapa", - "map-viewer": "Mapa" + "map-viewer": "Mapa", + "pinned-note": "Nota fijada" } diff --git a/tests/map-pins.test.js b/tests/map-pins.test.js new file mode 100644 index 00000000..1e466502 --- /dev/null +++ b/tests/map-pins.test.js @@ -0,0 +1,379 @@ +// Tests for the notes pinned onto a map (Syndria98/dragonroll#20): right clicking a map pins one of +// the campaign notes at that spot, and clicking the marker reads the linked note in a window. +// +// The repository root installs no dependencies, so both sides are loaded into `node:vm` contexts. +// The express routers run against a stubbed `require` (express itself, multer and the mongoose +// models) answering with plain objects: that keeps the ownership, same-campaign and dedup rules of +// POST /map/pin observable without a database. `frontend/app/services/MapPins.js` holds the image ↔ +// screen translation and the note picker labels, and is loaded the way map-viewer.test.js loads +// Content.js. The last checks read the template of the map viewer, because there the wiring itself +// is what has to stay right. +// +// 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"); + +function readRepoFile(...parts) { + return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8"); +} + +// A mongoose query answers whatever `await query` and `query.lean()` answer with, and lets `select()` +// and `sort()` sit in between. +function mongooseQuery(value) { + const result = { + select: () => result, + sort: () => result, + lean: () => Promise.resolve(value), + then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected), + }; + return result; +} + +// Loads an express router file with every module it requires stubbed out: `stubs` maps a require +// path ("../models/Map") to the module the route should see. +function loadRouter(relativeParts, stubs) { + const routes = new Map(); + const router = { + get: (route, ...handlers) => routes.set(`GET ${route}`, handlers), + post: (route, ...handlers) => routes.set(`POST ${route}`, handlers), + }; + + const requireStub = (id) => { + if (id === "express") return { Router: () => router }; + if (id === "../services/storage") return { single: () => (req, res, next) => next() }; + if (!(id in stubs)) throw new Error(`require("${id}") is not stubbed`); + return stubs[id]; + }; + + // Both files only need `require`, `module` and `exports`, so they are compiled as functions in + // the realm of the tests: the objects the routes build are then plain host objects to assert on. + const moduleStub = { exports: {} }; + vm.compileFunction(readRepoFile(...relativeParts), ["require", "module", "exports"])( + requireStub, moduleStub, moduleStub.exports + ); + + async function call(route, { body = {}, query = {}, params = {}, user = { id: "user-1" } } = {}) { + const handlers = routes.get(route); + assert.ok(handlers, `${route} is not mounted`); + const res = { payload: null, json(payload) { this.payload = payload; } }; + // The multer middleware the routes mount is stubbed away, so the handler is the last one. + await handlers[handlers.length - 1]({ body, query, params, user }, res); + return res.payload; + } + + return { routes, call }; +} + +function makeMap(pins = []) { + return { _id: "map-1", campaign: "campaign-1", pins, save: async () => {} }; +} + +function loadMapRoutes({ ownsCampaign = true, maps = [], notes = [] } = {}) { + return loadRouter(["backend", "src", "routes", "map.js"], { + "../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) }, + "../models/Map": { findById: (id) => mongooseQuery(maps.find((map) => map._id === id) ?? null) }, + "../models/Note": { + findOne: (filter) => mongooseQuery( + notes.some((note) => note._id === String(filter._id) && String(note.campaign) === String(filter.campaign)) + ? { _id: String(filter._id) } + : null + ), + }, + }); +} + +function mapPinRouteTests() { + test("pinning a note stores it at the spot that was clicked", async () => { + const map = makeMap(); + const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] }); + + const response = await api.call("POST /pin", { body: { id: "map-1", note: "note-1", x: 420, y: 96 } }); + + assert.equal(response.status, "ok"); + assert.deepEqual(map.pins, [{ note: "note-1", x: 420, y: 96 }]); + }); + + test("a pin keeps whole image pixels and never goes off the top left corner", async () => { + const map = makeMap(); + const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] }); + + // Coordinates arrive as strings from a multipart form, and a drag can leave the image. + await api.call("POST /pin", { body: { id: "map-1", note: "note-1", x: "120.6", y: -8 } }); + + assert.deepEqual(map.pins, [{ note: "note-1", x: 121, y: 0 }]); + }); + + test("a note of another campaign cannot be pinned onto a map", async () => { + const map = makeMap(); + const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-2", campaign: "campaign-2" }] }); + + const response = await api.call("POST /pin", { body: { id: "map-1", note: "note-2", x: 10, y: 10 } }); + + assert.equal(response.msg, "errors.notfound"); + assert.deepEqual(map.pins, []); + }); + + test("a map of somebody else's campaign answers unauthorized", async () => { + const map = makeMap(); + const api = loadMapRoutes({ ownsCampaign: false, maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] }); + + const response = await api.call("POST /pin", { body: { id: "map-1", note: "note-1", x: 10, y: 10 } }); + + assert.equal(response.msg, "unauthorized"); + assert.deepEqual(map.pins, []); + }); + + test("pinning a note again moves its marker instead of adding a twin", async () => { + const map = makeMap([{ _id: "pin-1", note: "note-1", x: 10, y: 10 }]); + const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] }); + + await api.call("POST /pin", { body: { id: "map-1", note: "note-1", x: 300, y: 220 } }); + + assert.equal(map.pins.length, 1); + assert.deepEqual({ ...map.pins[0] }, { _id: "pin-1", note: "note-1", x: 300, y: 220 }); + }); + + test("pinning needs both a map and a note", async () => { + const map = makeMap(); + const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] }); + + assert.equal((await api.call("POST /pin", { body: { note: "note-1", x: 1, y: 1 } })).msg, "errors.missing-data"); + assert.equal((await api.call("POST /pin", { body: { id: "map-1", x: 1, y: 1 } })).msg, "errors.missing-data"); + assert.deepEqual(map.pins, []); + }); + + test("unpin removes the pin it is given and keeps the others", async () => { + const map = makeMap([ + { _id: "pin-1", note: "note-1", x: 10, y: 10 }, + { _id: "pin-2", note: "note-2", x: 20, y: 20 }, + ]); + const api = loadMapRoutes({ maps: [map], notes: [] }); + + const response = await api.call("POST /unpin", { body: { id: "map-1", pin: "pin-1" } }); + + assert.equal(response.status, "ok"); + assert.deepEqual(map.pins.map((pin) => pin._id), ["pin-2"]); + }); + + test("unpin of a map of somebody else keeps its pins", async () => { + const map = makeMap([{ _id: "pin-1", note: "note-1", x: 10, y: 10 }]); + const api = loadMapRoutes({ ownsCampaign: false, maps: [map] }); + + const response = await api.call("POST /unpin", { body: { id: "map-1", pin: "pin-1" } }); + + assert.equal(response.msg, "unauthorized"); + assert.equal(map.pins.length, 1); + }); +} + +function loadNoteRoutes({ ownsCampaign = true, notes = [], folders = [], deletedCount = 1 } = {}) { + const pinsPulled = []; + const api = loadRouter(["backend", "src", "routes", "note.js"], { + "../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) }, + "../models/Note": { + find: () => mongooseQuery(notes), + findById: (id) => mongooseQuery(notes.find((note) => note._id === id) ?? null), + deleteOne: () => mongooseQuery({ deletedCount }), + }, + "../models/Folder": { find: () => mongooseQuery(folders) }, + "../models/Map": { + // The driver drops the pins of the note from every map holding one; what is worth + // keeping here is the filter it is asked to do that with. + updateMany: async (filter, update) => { + pinsPulled.push({ filter, update }); + return { modifiedCount: 1 }; + }, + }, + }); + return { api, pinsPulled }; +} + +function campaignNotesTests() { + const notes = [ + { _id: "note-1", title: "The Altar", folder: "folder-2" }, + { _id: "note-2", title: "The Inn", folder: null }, + ]; + const folders = [ + { _id: "folder-1", name: "Undercity" }, + { _id: "folder-2", name: "Temple", parentFolder: "folder-1" }, + ]; + + test("the note picker answers with every note and the folders they live in", async () => { + const { api } = loadNoteRoutes({ notes, folders }); + + const response = await api.call("GET /all", { query: { campaign: "campaign-1" } }); + + assert.equal(response.status, "ok"); + assert.deepEqual(response.notes.map((note) => note.title), ["The Altar", "The Inn"]); + assert.deepEqual(response.folders.map((folder) => folder.name), ["Undercity", "Temple"]); + }); + + test("the note picker needs a campaign, and only of one's own", async () => { + const { api } = loadNoteRoutes({ notes, folders }); + const { api: foreignCampaign } = loadNoteRoutes({ ownsCampaign: false, notes, folders }); + + assert.equal((await api.call("GET /all")).msg, "errors.missing-data"); + assert.equal((await foreignCampaign.call("GET /all", { query: { campaign: "campaign-1" } })).msg, "unauthorized"); + }); + + test("a note can be read on its own, the way a map pin asks for it", async () => { + const { api } = loadNoteRoutes({ notes: [{ _id: "note-1", title: "The Altar", content: "## The altar" }] }); + + const response = await api.call("GET /retrieve/:id", { params: { id: "note-1" } }); + + assert.equal(response.status, "ok"); + assert.equal(response.note.content, "## The altar"); + }); + + test("a note of a campaign the user does not own cannot be read", async () => { + const { api } = loadNoteRoutes({ ownsCampaign: false, notes: [{ _id: "note-1", title: "The Altar" }] }); + + const response = await api.call("GET /retrieve/:id", { params: { id: "note-1" } }); + + assert.equal(response.msg, "unauthorized"); + }); + + test("deleting a note pulls the pins pointing at it", async () => { + const { api, pinsPulled } = loadNoteRoutes({ notes: [{ _id: "note-1", title: "The Altar" }] }); + + const response = await api.call("POST /delete", { body: { id: "note-1" } }); + + assert.equal(response.status, "ok"); + assert.deepEqual(pinsPulled, [{ filter: { "pins.note": "note-1" }, update: { $pull: { pins: { note: "note-1" } } } }]); + }); + + test("deleting a note that is not there does not touch any map", async () => { + const { api, pinsPulled } = loadNoteRoutes({ notes: [], deletedCount: 0 }); + + const response = await api.call("POST /delete", { body: { id: "note-9" } }); + + assert.equal(response.msg, "errors.notfound"); + assert.deepEqual(pinsPulled, []); + }); +} + +function loadMapPinsService() { + const source = readRepoFile("frontend", "app", "services", "MapPins.js"); + const body = source + .replace(/import\s*\{[^}]*\}\s*from\s*['"]vue['"];?/, "") + .replace(/export\s*\{/, "return {") + .concat("\n;"); + + return vm.compileFunction(body, [])(); +} + +function mapPinsServiceTests() { + const service = loadMapPinsService(); + // 800x600 image, shown at 200% and panned so its top left corner sits at (20, 10) of the viewport. + const view = { zoom: 2, pan: { x: 20, y: 10 }, width: 800, height: 600 }; + + test("a spot of the viewport becomes the pixel of the image it stands for", () => { + assert.deepEqual(service.ToImagePoint({ x: 100, y: 50 }, view), { x: 40, y: 20 }); + }); + + test("spots outside the image pin nothing", () => { + assert.equal(service.ToImagePoint({ x: 10, y: 50 }, view), null); + assert.equal(service.ToImagePoint({ x: 100, y: -5 }, view), null); + assert.equal(service.ToImagePoint({ x: 1700, y: 50 }, view), null); + }); + + test("without a loaded image there is no spot to pin", () => { + assert.equal(service.ToImagePoint({ x: 100, y: 50 }, { zoom: 1, pan: { x: 0, y: 0 }, width: 0, height: 0 }), null); + assert.equal(service.ToImagePoint({ x: 100, y: 50 }, undefined), null); + }); + + test("a pin lands on the same spot of the screen it was placed at", () => { + // An even spot: the image pixels of a pin are rounded, so the round trip is exact there. + const spot = service.ToImagePoint({ x: 370, y: 124 }, view); + assert.deepEqual(spot, { x: 175, y: 57 }); + assert.deepEqual(service.ToScreenPoint(spot, view), { x: 370, y: 124 }); + }); + + test("pins follow the map but keep their own size", () => { + // Only the position scales: the marker itself is drawn outside of the scaled stage. + assert.deepEqual(service.ToScreenPoint({ x: 40, y: 20 }, { ...view, zoom: 4 }), { x: 180, y: 90 }); + assert.deepEqual(service.ToScreenPoint({ x: 40, y: 20 }, { ...view, pan: { x: -40, y: 0 } }), { x: 40, y: 40 }); + }); + + test("notes of a folder are labelled with where they live", () => { + const options = service.BuildNoteOptions( + [{ _id: "note-1", title: "The Altar", folder: "folder-2" }, { _id: "note-2", title: "The Inn", folder: null }], + [{ _id: "folder-1", name: "Undercity" }, { _id: "folder-2", name: "Temple", parentFolder: "folder-1" }] + ); + + assert.deepEqual(options.map((option) => option.label), ["The Inn", "Undercity / Temple / The Altar"]); + assert.equal(options.find((option) => option.value === "note-1").path, "Undercity / Temple"); + }); + + test("the picker is sorted by the label it shows, not by the bare title", () => { + const options = service.BuildNoteOptions( + [{ _id: "note-1", title: "Bridge", folder: null }, { _id: "note-2", title: "Altar", folder: "folder-1" }], + [{ _id: "folder-1", name: "Cave" }] + ); + + // "Altar" would lead the menu by title, but it is nowhere near it once its folder is named. + assert.deepEqual(options.map((option) => option.value), ["note-1", "note-2"]); + }); + + test("a note without a title is left out of the picker", () => { + const options = service.BuildNoteOptions([{ _id: "note-1", title: " " }], []); + + assert.deepEqual(options, []); + }); + + test("a broken folder chain cannot loop the picker", () => { + const options = service.BuildNoteOptions( + [{ _id: "note-1", title: "The Altar", folder: "folder-1" }], + [{ _id: "folder-1", name: "One", parentFolder: "folder-2" }, { _id: "folder-2", name: "Two", parentFolder: "folder-1" }] + ); + + assert.equal(options[0].label, "Two / One / The Altar"); + }); + + test("renaming a note keeps the folder path of its label", () => { + const option = { value: "note-1", title: "The Altar", path: "Undercity / Temple" }; + option.title = "The Ruined Altar"; + + assert.equal(service.OptionLabel(option), "Undercity / Temple / The Ruined Altar"); + }); +} + +function mapViewerWiringTests() { + const pane = readRepoFile("frontend", "app", "components", "viewer", "map", "MapViewerPane.vue"); + const definitions = readRepoFile("frontend", "app", "services", "WindowDefinitions.js"); + const windowSource = readRepoFile("frontend", "app", "components", "windows", "PinnedNoteWindow.vue"); + + test("right clicking the map opens the pin menu", () => { + const viewport = /]*ref="viewport"[^>]*>/.exec(pane)?.[0]; + assert.ok(viewport, "expected the map viewport element"); + assert.match(viewport, /@contextmenu\.prevent="onMapContextMenu"/); + }); + + test("pins are drawn in screen space and only they catch the mouse", () => { + // Inside the scaled stage the markers would shrink and grow with the map instead of staying + // where they were placed; the overlay must not take the mouse away from panning. + assert.match(pane, /class="map-pin"[^>]*:style="pinStyle\(pin\)"/); + assert.match(pane, /\.map-pins\s*\{[^}]*pointer-events:\s*none/); + assert.match(pane, /\.map-pin\s*\{[^}]*pointer-events:\s*auto/); + }); + + test("a pin opens the linked note and does not start a pan", () => { + assert.match(pane, /@pointerdown\.stop/); + assert.match(pane, /@click="openPinnedNote\(pin\)"/); + assert.match(pane, /CreateWindow\('pinned_note'/); + }); + + test("the pinned note window is registered and reads the note from the server", () => { + assert.match(definitions, /pinned_note:\s*\{[^}]*windows\.pinned-note[^}]*PinnedNoteWindow\.vue/s); + assert.match(windowSource, /get\(`\/note\/retrieve\/\$\{noteId\}`\)/); + }); +} + +mapPinRouteTests(); +campaignNotesTests(); +mapPinsServiceTests(); +mapViewerWiringTests();