Merge pull request 'Fix #20: Add notes to a map' (#23) from ai/issue-20 into master
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m5s

Reviewed-on: #23
This commit was merged in pull request #23.
This commit is contained in:
2026-10-14 16:30:54 +00:00
16 changed files with 922 additions and 14 deletions

View File

@@ -159,7 +159,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` | | `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` | | `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` | | `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. `*` = required. Notes and folders are ordered by `date: -1` everywhere.
@@ -193,9 +193,12 @@ Fetch the file from `/api/public/<filename>`.
`GET /api/note/list?campaign=` → `{status:'ok', folders, notes}` — notes with `folder: null` (roots); `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 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/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/create` — `{title*,content,campaign*,folder?}` (folder validated against campaign)
`POST /api/note/update` — `{id*, title?, content?, folder?, color?}` — partial, ownership checked `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}` `GET /api/folder/list?campaign=` → `{status:'ok',folders}`
`POST /api/folder/create` — `{name*,campaign*}` `POST /api/folder/create` — `{name*,campaign*}`
@@ -222,6 +225,9 @@ subfolders re-parented to null then deleted.
`POST /api/map/update` — `{id*, name?, gridSize?, offsetX?, offsetY?, scale?}`, partial, ownership checked. Send it as `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). 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/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) ### 4.1 Foundry integration (actors, items)
@@ -309,7 +315,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 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 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 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()`): Boot sequence (`app.vue` → `start()`):
@@ -428,8 +437,8 @@ Every listener in the app (there are only these six `emitter.on` call sites):
| `toast` | `{color,text,duration}` | `ToastManager.vue` | | `toast` | `{color,text,duration}` | `ToastManager.vue` |
| `push-note` | `{key,title,text,date}` | `NoteContainer.vue` | | `push-note` | `{key,title,text,date}` | `NoteContainer.vue` |
| `close-note` | note key (string) | `NoteContainer.vue` (removes the note from the open column only) | | `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) | | `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` | | `title-updated` | `{key,title}` | `Note.vue`, `NoteContainer.vue`, `MapViewerPane.vue` (relabels the map pins of that note) |
| `status-bar-update` | `{text,icon}` | `FetchStatus.vue` | | `status-bar-update` | `{text,icon}` | `FetchStatus.vue` |
Emitters: `Toaster.js` (`toast`), `ContentSidebar` / `TopSearchBar` (`push-note`), `Note.vue` Emitters: `Toaster.js` (`toast`), `ContentSidebar` / `TopSearchBar` (`push-note`), `Note.vue`

View File

@@ -12,6 +12,13 @@ const MapSchema = new Schema({
offsetY: { type: Number, default: 0 }, offsetY: { type: Number, default: 0 },
// Distance each grid cell stands for (feet, metres...) // Distance each grid cell stands for (feet, metres...)
scale: { type: Number, min: 0.01, default: 5 }, 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: { campaign: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: 'Campaign', ref: 'Campaign',

View File

@@ -5,6 +5,7 @@ const upload = require('../services/storage');
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Map = require('../models/Map'); const Map = require('../models/Map');
const Note = require('../models/Note');
async function userOwnsCampaign(campaignId, userId) { async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); 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; module.exports = router;

View File

@@ -4,6 +4,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign'); const Campaign = require('../models/Campaign');
const Note = require('../models/Note'); const Note = require('../models/Note');
const Folder = require('../models/Folder'); const Folder = require('../models/Folder');
const Map = require('../models/Map');
async function userOwnsCampaign(campaignId, userId) { async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); 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) => { router.post('/create', async (req, res) => {
try { try {
const { title, content, campaign, folder } = req.body; const { title, content, campaign, folder } = req.body;
@@ -119,6 +163,9 @@ router.post('/delete', async (req, res) => {
const result = await Note.deleteOne({ _id: id }); const result = await Note.deleteOne({ _id: id });
if (result.deletedCount === 0) return res.json({ status: 'error', msg: 'errors.notfound' }); 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' }); res.json({ status: 'ok' });
} catch (err) { } catch (err) {
console.error(err); console.error(err);

View File

@@ -120,6 +120,9 @@ function handleCampaignEntryUpdated({ entityType, entry }) {
if (!list) return; if (!list) return;
list.value = list.value.map((current) => current._id === entry._id ? entry : current) list.value = list.value.map((current) => current._id === entry._id ? entry : current)
.sort((a, b) => a.name.localeCompare(b.name)); .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(() => { const campaignId = computed(() => {

View File

@@ -1,7 +1,11 @@
<script setup> <script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'; import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { CreateWindow } from '@/services/Windows'; import { useI18n } from 'vue-i18n';
import { getBaseUrl } from '~/services/Server'; import { ClearWindow, CreateWindow, GetFirstWindowId } from '@/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
import { BuildNoteOptions, OptionLabel, ToImagePoint, ToScreenPoint } from '~/services/MapPins';
import { DisplayToast } from '~/services/Toaster';
import Server, { getBaseUrl } from '~/services/Server';
import { emitter } from '~/services/Emitter'; import { emitter } from '~/services/Emitter';
import { useCampaignService } from '~/services/Campaign.js'; import { useCampaignService } from '~/services/Campaign.js';
@@ -141,6 +145,135 @@ function handleMapUpdated({ entityType, entry }) {
if (imageChanged) imageSize.value = { width: 0, height: 0 }; if (imageChanged) imageSize.value = { width: 0, height: 0 };
} }
// --- Notes pinned onto the map ---
// Right clicking the map pins one of the campaign notes at that spot, and clicking the marker reads
// it in a window of its own.
const { t } = useI18n();
const noteOptions = ref([]);
const pins = computed(() => map.value?.pins ?? []);
const labelByNoteId = computed(() => new Map(noteOptions.value.map((option) => [option.value, option.label])));
// What the pin helpers need to know about the current view to translate between image and screen.
function viewState() {
return { zoom: zoom.value, pan: pan.value, width: imageSize.value.width, height: imageSize.value.height };
}
function pinStyle(pin) {
const point = ToScreenPoint(pin, viewState());
return { left: `${point.x}px`, top: `${point.y}px` };
}
function pinLabel(pin) {
return labelByNoteId.value.get(String(pin?.note)) ?? '';
}
// Every note of the campaign, so notes living in a folder can be pinned too and every marker can
// say which note it is.
async function fetchPinnableNotes() {
if (!campaignId.value) {
noteOptions.value = [];
return;
}
try {
const response = await Server().get('/note/all', { params: { campaign: campaignId.value } });
noteOptions.value = response.data.status === 'ok'
? BuildNoteOptions(response.data.notes, response.data.folders)
: [];
} catch (error) {
noteOptions.value = [];
}
}
function onMapContextMenu(event) {
// A pin marks a spot on the image, so there is nothing to pin while the map has no image.
const bounds = viewport.value?.getBoundingClientRect();
if (!imageUrl.value || !bounds) return;
// Reaching a submenu moves the mouse away from the spot, so it is kept for the menu actions.
const spot = ToImagePoint({ x: event.clientX - bounds.left, y: event.clientY - bounds.top }, viewState());
if (!spot) return;
if (!noteOptions.value.length) {
ShowContextMenu([{ name: t('campaigns.map.pins.none'), action: () => HideContextMenu() }]);
return;
}
ShowContextMenu([{
name: t('campaigns.map.pins.add'),
icon: '/icons/iconoir/regular/map-pin-plus.svg',
context: noteOptions.value.map((option) => ({
name: option.label,
icon: '/icons/iconoir/regular/notes.svg',
action: () => { HideContextMenu(); savePin(option.value, spot); }
}))
}]);
}
function onPinContextMenu(pin) {
ShowContextMenu([
{
name: t('campaigns.map.pins.open'),
icon: '/icons/iconoir/regular/notes.svg',
action: () => { HideContextMenu(); openPinnedNote(pin); }
},
{ divider: true },
{
name: t('campaigns.map.pins.remove'),
icon: '/icons/iconoir/regular/map-pin-xmark.svg',
action: () => { HideContextMenu(); removePin(pin); }
}
]);
}
async function savePin(noteId, spot) {
await updatePins('/map/pin', { id: map.value?._id, note: noteId, x: spot.x, y: spot.y });
}
async function removePin(pin) {
await updatePins('/map/unpin', { id: map.value?._id, pin: pin?._id });
}
// Both pin changes answer with the whole map, which keeps the sidebar entry and the anchored map in
// step with what is on screen.
async function updatePins(route, body) {
if (!body.id) return;
try {
const response = await Server().post(route, body);
if (response.data.status !== 'ok') {
DisplayToast('red', t('campaigns.map.pins.error'), 3000);
return;
}
map.value = { ...response.data.map };
emitter.emit('campaign-entry-updated', { entityType: 'map', entry: response.data.map });
} catch (error) {
DisplayToast('red', t('campaigns.map.pins.error'), 3000);
}
}
async function openPinnedNote(pin) {
if (!pin?.note) return;
// One window reads the pinned notes; opening another one replaces it, like the character sheet.
const existingWindowId = GetFirstWindowId('pinned_note');
if (existingWindowId !== undefined) ClearWindow({ id: existingWindowId });
await nextTick();
CreateWindow('pinned_note', { note: pin.note });
}
// The backend drops the pins of a note along with it; the markers on this open map follow at once.
function handlePinnedNoteDeleted(noteKey) {
if (!pins.value.length) return;
const remaining = map.value.pins.filter((pin) => String(pin.note) !== String(noteKey));
if (remaining.length !== map.value.pins.length) map.value = { ...map.value, pins: remaining };
}
function handlePinnedNoteRenamed({ key, title }) {
const option = noteOptions.value.find((current) => current.value === String(key));
if (!option) return;
option.title = title;
option.label = OptionLabel(option);
}
// A different map was anchored while this pane was already mounted. // A different map was anchored while this pane was already mounted.
watch(() => props.map, (incoming, previous) => { watch(() => props.map, (incoming, previous) => {
if (incoming === previous) return; if (incoming === previous) return;
@@ -148,12 +281,22 @@ watch(() => props.map, (incoming, previous) => {
imageSize.value = { width: 0, height: 0 }; imageSize.value = { width: 0, height: 0 };
}); });
watch(campaignId, () => {
noteOptions.value = [];
fetchPinnableNotes();
});
onMounted(() => { onMounted(() => {
emitter.on('campaign-entry-updated', handleMapUpdated); emitter.on('campaign-entry-updated', handleMapUpdated);
emitter.on('delete-note', handlePinnedNoteDeleted);
emitter.on('title-updated', handlePinnedNoteRenamed);
fetchPinnableNotes();
}); });
onBeforeUnmount(() => { onBeforeUnmount(() => {
emitter.off('campaign-entry-updated', handleMapUpdated); emitter.off('campaign-entry-updated', handleMapUpdated);
emitter.off('delete-note', handlePinnedNoteDeleted);
emitter.off('title-updated', handlePinnedNoteRenamed);
}); });
</script> </script>
@@ -198,10 +341,28 @@ onBeforeUnmount(() => {
@pointermove="onPointerMove" @pointermove="onPointerMove"
@pointerup="onPointerUp" @pointerup="onPointerUp"
@pointercancel="onPointerUp" @pointercancel="onPointerUp"
@contextmenu.prevent="onMapContextMenu"
> >
<template v-if="imageUrl"> <template v-if="imageUrl">
<img class="map-image" :src="imageUrl" :style="stageStyle" :alt="map?.name" draggable="false" @load="onImageLoaded"> <img class="map-image" :src="imageUrl" :style="stageStyle" :alt="map?.name" draggable="false" @load="onImageLoaded">
<div class="map-grid" :style="gridStyle" aria-hidden="true"></div> <div class="map-grid" :style="gridStyle" aria-hidden="true"></div>
<div class="map-pins">
<button
v-for="pin in pins"
:key="pin._id"
class="map-pin"
type="button"
:style="pinStyle(pin)"
:title="pinLabel(pin) || $t('campaigns.map.pins.open')"
:aria-label="pinLabel(pin) || $t('campaigns.map.pins.open')"
@pointerdown.stop
@click="openPinnedNote(pin)"
@contextmenu.stop.prevent="onPinContextMenu(pin)"
>
<img class="pin-icon" src="/icons/iconoir/solid/pin.svg" alt="" aria-hidden="true">
<span class="pin-label">{{ pinLabel(pin) }}</span>
</button>
</div>
</template> </template>
<div v-else class="map-empty"> <div v-else class="map-empty">
{{ $t('campaigns.map.no-image') }} {{ $t('campaigns.map.no-image') }}
@@ -227,6 +388,22 @@ onBeforeUnmount(() => {
.map-viewport.dragging { cursor: grabbing; } .map-viewport.dragging { cursor: grabbing; }
.map-image { position: absolute; top: 0; left: 0; max-width: none; transform-origin: top left; user-select: none; } .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; } .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-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 { 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); } .map-edit:hover { background: var(--color-button-hover); }

View File

@@ -0,0 +1,122 @@
<script setup>
import { createApp, onBeforeUnmount, onMounted, ref } from 'vue';
import { SetupHandle, SetSize, ResetPosition, ClearWindow, Top } from '@/services/Windows';
import WindowHandle from './partials/WindowHandle.vue';
import { GetWidget, ParseMarkdown } from '~/services/Marker';
import Server from '~/services/Server';
// The note a map pin points at (see MapViewerPane.vue). The note is fetched here instead of being
// carried over from the map, so a pin works whatever the note column shows and always reads fresh.
const props = defineProps(['data']);
const id = props.data.id;
const noteId = props.data.note;
const handle = ref(null);
const wrapper = ref(null);
const renderedContent = ref(null);
const note = ref(null);
const displayText = ref('');
const loading = ref(true);
const failed = ref(false);
// Widgets mounted over this note, kept to unmount them again the way Note.vue does: re-rendering
// would otherwise leave the apps of the nodes it replaced behind.
const mountedApps = [];
function unmountWidgets() {
for (const app of mountedApps) {
try {
app.unmount();
} catch (error) {
// The container may already be off the DOM; ignore and drop it all the same.
}
}
mountedApps.length = 0;
}
function mountWidgets() {
const root = renderedContent.value;
if (!root) return;
['display', 'inline'].forEach((widgetType) => {
root.querySelectorAll('.vue-component-' + widgetType).forEach((el) => {
const widget = GetWidget(widgetType, el.dataset.component);
if (!widget) return;
try {
const app = createApp(widget, { content: el.dataset.content });
app.config.errorHandler = (error) => console.error('Widget error', el.dataset.component, error);
app.mount(el);
mountedApps.push(app);
} catch (error) {
console.error('Failed to mount widget', el.dataset.component, error);
}
});
});
}
async function fetchNote() {
loading.value = true;
failed.value = false;
try {
const response = await Server().get(`/note/retrieve/${noteId}`);
if (response.data.status !== 'ok' || !response.data.note) {
failed.value = true;
return;
}
note.value = response.data.note;
unmountWidgets();
displayText.value = ParseMarkdown(response.data.note.content ?? '');
setTimeout(() => mountWidgets(), 0);
} catch (error) {
failed.value = true;
} finally {
loading.value = false;
}
}
onMounted(() => {
Top(wrapper);
SetupHandle(id, handle);
SetSize(id, {
width: Math.max(360, Math.min(720, window.innerWidth - 24)),
height: Math.max(360, Math.min(720, window.innerHeight - 32))
});
ResetPosition(id, 'center');
fetchNote();
});
onBeforeUnmount(() => {
unmountWidgets();
ClearWindow({ type: 'pinned_note' });
});
</script>
<template>
<div class="window-wrapper pinned-note-window" :id="'window-wrapper-' + id" ref="wrapper">
<WindowHandle :window="id" ref="handle" />
<div class="body">
<div v-if="loading" class="note-state">{{ $t('campaigns.states.loading') }}</div>
<div v-else-if="failed" class="note-state">{{ $t('campaigns.map.pins.note-error') }}</div>
<template v-else>
<h1 v-if="note.title" class="note-title">{{ note.title }}</h1>
<div ref="renderedContent" class="note-content" v-html="displayText"></div>
</template>
</div>
</div>
</template>
<style scoped>
.window-wrapper { display: flex; align-items: center; flex-direction: column; }
/* Stretch so the outer margin insets the content instead of overflowing the window. */
.body {
flex: 1;
min-height: 0;
align-self: stretch;
box-sizing: border-box;
margin: 10px;
padding: 8px;
overflow-y: auto;
}
.note-title { margin: 0 0 10px; font-family: MrEavesRemake; overflow-wrap: anywhere; }
.note-state { padding: 10px; font-size: 13px; opacity: .8; }
.note-content :deep(img) { max-width: 100%; height: auto; display: block; }
</style>

View File

@@ -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
};

View File

@@ -82,6 +82,12 @@ const defWindows = {
component: () => import('~/components/windows/MapViewerWindow.vue'), component: () => import('~/components/windows/MapViewerWindow.vue'),
close: () => ClearWindow({type: 'map_viewer'}), close: () => ClearWindow({type: 'map_viewer'}),
movable: true movable: true
},
pinned_note: {
title: 'windows.pinned-note',
component: () => import('~/components/windows/PinnedNoteWindow.vue'),
close: () => ClearWindow({type: 'pinned_note'}),
movable: true
} }
} }

View File

@@ -78,7 +78,13 @@
"save-error": "No s'ha pogut desar aquest mapa.", "save-error": "No s'ha pogut desar aquest mapa.",
"no-image": "Aquest mapa encara no té imatge.", "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", "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": { "character-sheet": {
"title": "Fitxa de personatge", "name": "Nom del personatge", "class": "Classe", "subclass": "Subclasse", "unset-class": "Classe sense definir", "title": "Fitxa de personatge", "name": "Nom del personatge", "class": "Classe", "subclass": "Subclasse", "unset-class": "Classe sense definir",

View File

@@ -7,5 +7,6 @@
"settings": "Configuració", "settings": "Configuració",
"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"
} }

View File

@@ -82,7 +82,13 @@
"save-error": "Unable to save this map.", "save-error": "Unable to save this map.",
"no-image": "This map has no image yet.", "no-image": "This map has no image yet.",
"zoom-in": "Zoom in", "zoom-out": "Zoom out", "fit": "Fit to window", "toggle-grid": "Show grid", "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": { "character-sheet": {
"title": "Character Sheet", "name": "Character name", "class": "Class", "subclass": "Subclass", "unset-class": "Class not set", "title": "Character Sheet", "name": "Character name", "class": "Class", "subclass": "Subclass", "unset-class": "Class not set",

View File

@@ -7,5 +7,6 @@
"settings": "Settings", "settings": "Settings",
"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"
} }

View File

@@ -78,7 +78,13 @@
"save-error": "No se pudo guardar este mapa.", "save-error": "No se pudo guardar este mapa.",
"no-image": "Este mapa aún no tiene imagen.", "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", "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": { "character-sheet": {
"title": "Hoja de personaje", "name": "Nombre del personaje", "class": "Clase", "subclass": "Subclase", "unset-class": "Clase sin definir", "title": "Hoja de personaje", "name": "Nombre del personaje", "class": "Clase", "subclass": "Subclase", "unset-class": "Clase sin definir",

View File

@@ -7,5 +7,6 @@
"settings": "Configuración", "settings": "Configuración",
"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"
} }

379
tests/map-pins.test.js Normal file
View File

@@ -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 = /<div[^>]*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();