From d567b5d1711b141fc102461b4e7c190c9c80ecd2 Mon Sep 17 00:00:00 2001 From: Gitea OpenCode Agent Date: Wed, 14 Oct 2026 18:41:17 +0000 Subject: [PATCH] Fix issue #38: Implement tokens on maps --- AGENTS.md | 12 +- backend/src/models/Map.js | 8 + backend/src/routes/actor.js | 6 + backend/src/routes/map.js | 71 +++- .../components/partials/ContentSidebar.vue | 11 +- .../components/viewer/map/MapViewerPane.vue | 302 ++++++++++++++- frontend/app/services/MapTokens.js | 69 ++++ frontend/i18n/locales/ca/campaigns.json | 6 + frontend/i18n/locales/en/campaigns.json | 6 + frontend/i18n/locales/es/campaigns.json | 6 + tests/map-pins.test.js | 2 + tests/map-tokens.test.js | 344 ++++++++++++++++++ 12 files changed, 826 insertions(+), 17 deletions(-) create mode 100644 frontend/app/services/MapTokens.js create mode 100644 tests/map-tokens.test.js diff --git a/AGENTS.md b/AGENTS.md index b911380b..773ada40 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ items, maps, dice widgets, sounds). - `discord-bot/` — Discord bot (slash commands) that talks to the backend with a shared service secret, no login. - `dragonroll-foundry/` — Foundry VTT module (`scripts/api.js`) + optional read-only snapshot bridge. - `obsidian-plugin/` — plain JavaScript Obsidian plugin that imports/pushes campaign notes. -- `tests/` — `npm test` (`node --test`, no dependencies installed): Foundry sync toggle and pairing status, map pins, sidebar entries. +- `tests/` — `npm test` (`node --test`, no dependencies installed): Foundry sync toggle and pairing status, map pins and tokens, sidebar entries. No DB seeding, no migrations, no linter/formatter, no Pinia/Vuex. Git: default branch `master` on a self-hosted Gitea; `.gitea/workflows/deploy.yml` builds and deploys Docker images on push to `master`, @@ -87,7 +87,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user - `Folder` — `name*`, `campaign*`, `parentFolder` (null = root, self-ref), `color` - `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), plus free-form sheet fields (`type`, `species`, `className`, `level`, `abilityScores`, `armorClass`, `speed`, `proficiencies`, `traits`, `spells`, `image`) and `inventory[{name,quantity,weight}]` (flattened Foundry items, **not** `Item` docs) - `Item` — `name*`, `campaign*`, `foundryItemId` (unique per campaign), `foundryNames`, `category`, `rarity`, `quantity`, `weight`, `properties`, `description` -- `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`), `gridSize`/`offsetX`/`offsetY`/`scale` (image px), `pins[{note→Note, x, y}]` (addressed by the pin's own `_id`) +- `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`), `gridSize`/`offsetX`/`offsetY`/`scale` (image px), `pins[{note→Note, x, y}]` (addressed by the pin's own `_id`), `tokens[{actor→Actor, x, y}]` (the centre of the grid cell the token stands in, also addressed by its own `_id`) - `ServiceLinkRequest` — the pending/completed service pairings of §4; `DiscordGuildLink` maps a Discord guild to the Dragonroll user who claimed it **API surface** (all under `/api`, all `{status,msg}`): @@ -98,7 +98,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user - `folder` — `list`, `create`, `update`, `rename`, `delete` (recursive: inner notes go to `folder: null`, subfolders re-parent then delete) - `actor` — `list`, `create`, `update` (partial, ownership checked), `upload-image?actor=` (multipart), `delete` - `item` — `list`, `create`, `update` (partial), `delete` -- `map` — `list`, `create` (multipart `image` or JSON), `update` (multipart to replace the photo), `delete`, `pin` (`{id,note,x,y}`, re-pinning moves the marker), `unpin` (`{id,pin}`) +- `map` — `list`, `create` (multipart `image` or JSON), `update` (multipart to replace the photo), `delete`, `pin` (`{id,note,x,y}`, re-pinning moves the marker), `unpin` (`{id,pin}`), `place-token` (`{id,actor,x,y}`, snapped to a cell centre, re-placing moves the token), `remove-token` (`{id,token}`) - `foundry` — read-only proxy over the bridge (`/world`, `/actors`, `/characters`, `/items`, `/actors/:id`, `/items/:id`, `/actors/:id/items`), needs `FOUNDRY_API_URL` ## 4. Service integrations (Foundry, Discord, Obsidian) @@ -138,7 +138,9 @@ campaign workspace (`TopBar` + `ContentSidebar` + note column + `StatusBar`), tu (`ActivePane` / `AnchoredMap` / `AnchorMap` in `services/Content.js`); `viewer/map/MapViewerPane.vue` renders it both there and in the detached `map_viewer` window. Right-clicking that map pins a campaign note at the spot (`services/MapPins.js` translates image px ↔ screen), clicking the marker opens -`pinned_note`. +`pinned_note`. Dragging an actor row out of the sidebar onto the map makes it stand on that grid cell +as a token (`services/MapTokens.js` snaps to cell centres and sizes the token by its cell); the token +drags on with the pointer, steps over the grid with the arrow keys, and Delete takes it off. ### 5.2 The window system @@ -162,7 +164,7 @@ DOM ids these services depend on — **do not rename**: `window-wrapper-{id}`, ` writes `localStorage.selectedCampaignId`, `RestoreCampaign`), `Content.js` (§5.1), `Emitter.js` (`mitt()` bus), `Toaster.js`, `Tooltip.js`, `ContextMenu.js`, `Sound.js` (`AddSound` binds `snap.wav` to `.sound-click`), `Marker.js` (marked + widgets), `ActionRegistry.js` (command palette: -`register/unregister/search/execute`), `Windows.js` / `WindowDefinitions.js`, `MapPins.js`, +`register/unregister/search/execute`), `Windows.js` / `WindowDefinitions.js`, `MapPins.js`, `MapTokens.js`, `widgets/DiceParser.js`. ### 5.4 Markdown → widgets diff --git a/backend/src/models/Map.js b/backend/src/models/Map.js index e9176db5..f18ce092 100644 --- a/backend/src/models/Map.js +++ b/backend/src/models/Map.js @@ -19,6 +19,14 @@ const MapSchema = new Schema({ x: { type: Number, default: 0 }, y: { type: Number, default: 0 } }], + // Actors dragged onto the map to stand on it as tokens. x/y are image pixels of the centre of the + // token, like a pin, and the viewer keeps them snapped onto a grid cell so a token sits where the + // square it stands in is. + tokens: [{ + actor: { type: Schema.Types.ObjectId, ref: 'Actor', 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/actor.js b/backend/src/routes/actor.js index 952efb8a..f48fdea4 100644 --- a/backend/src/routes/actor.js +++ b/backend/src/routes/actor.js @@ -5,6 +5,7 @@ const upload = require('../services/storage'); const Campaign = require('../models/Campaign'); const Actor = require('../models/Actor'); +const Map = require('../models/Map'); async function userOwnsCampaign(campaignId, userId) { const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); @@ -101,6 +102,11 @@ router.post('/delete', async (req, res) => { if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' }); if (!(await userOwnsCampaign(actor.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' }); await actor.deleteOne(); + + // A token pointing at an actor that is gone would stand on the maps for nothing: drop those + // along with the actor, like the pins of a deleted note. + await Map.updateMany({ 'tokens.actor': id }, { $pull: { tokens: { actor: id } } }); + res.json({ status: 'ok' }); } catch (err) { console.error(err); diff --git a/backend/src/routes/map.js b/backend/src/routes/map.js index 0d391db3..f7cac9f6 100644 --- a/backend/src/routes/map.js +++ b/backend/src/routes/map.js @@ -6,6 +6,7 @@ const upload = require('../services/storage'); const Campaign = require('../models/Campaign'); const Map = require('../models/Map'); const Note = require('../models/Note'); +const Actor = require('../models/Actor'); async function userOwnsCampaign(campaignId, userId) { const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean(); @@ -93,8 +94,9 @@ 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. +// A pin is a note placed at a spot of the map, in image pixels, and so is the centre of a token. +// 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; @@ -152,4 +154,69 @@ router.post('/unpin', async (req, res) => { } }); +// A token is an actor standing on the map, at the middle of a grid cell. Anywhere it is dropped in a +// cell lands it in that cell, whatever the grid is drawn from: same rounding as the viewer does while +// it drags, so the token does not jump when the move is saved. +function toCellCoordinate(value, size, offset) { + const grid = Math.max(1, Number(size) || 50); + const origin = Number(offset) || 0; + const cell = Math.floor((toCoordinate(value) - origin) / grid); + return Math.max(0, Math.round(origin + (cell + 0.5) * grid)); +} + +router.post('/place-token', async (req, res) => { + try { + const { id, actor, x, y } = req.body; + if (!id || !actor) 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 an actor of the same campaign can stand on one of its maps. + const actorDoc = await Actor.findOne({ _id: actor, campaign: map.campaign }).select('_id').lean(); + if (!actorDoc) return res.json({ status: 'error', msg: 'errors.notfound' }); + + // An actor stands on a map once: placing it again moves its token instead of adding a twin. + const token = map.tokens.find((current) => String(current.actor) === String(actor)); + const spot = { + x: toCellCoordinate(x, map.gridSize, map.offsetX), + y: toCellCoordinate(y, map.gridSize, map.offsetY) + }; + if (token) { + token.x = spot.x; + token.y = spot.y; + } else { + map.tokens.push({ actor, ...spot }); + } + + await map.save(); + res.json({ status: 'ok', map }); + } catch (err) { + console.error(err); + res.json({ status: 'error', msg: 'errors.internal' }); + } +}); + +router.post('/remove-token', async (req, res) => { + try { + const { id, token } = req.body; + if (!id || !token) 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 tokens that remain, the same way the pins are removed. + map.tokens = map.tokens + .filter((current) => String(current._id) !== String(token)) + .map((current) => ({ _id: current._id, actor: current.actor, 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/frontend/app/components/partials/ContentSidebar.vue b/frontend/app/components/partials/ContentSidebar.vue index 6cf124b1..07315317 100644 --- a/frontend/app/components/partials/ContentSidebar.vue +++ b/frontend/app/components/partials/ContentSidebar.vue @@ -8,6 +8,7 @@ import { emitter } from '~/services/Emitter'; import Server from '~/services/Server'; import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows'; import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu'; +import { ACTOR_DRAG_TYPE } from '~/services/MapTokens'; import NestedNoteList from './NestedNoteList.vue'; const { Campaign } = useCampaignService(); @@ -44,6 +45,14 @@ async function handleSidebarDrop(event) { } catch (e) {} } +// An actor row is dragged out of the sidebar onto a map, where it stands as a token. The map viewer +// reads that type back on its drop (see MapViewerPane.vue); a note drag carries 'text/plain' +// instead, so the two never land where the other belongs. +function startActorDrag(event, actor) { + event.dataTransfer.setData(ACTOR_DRAG_TYPE, String(actor._id)); + event.dataTransfer.effectAllowed = 'copyMove'; +} + function toggleExpandedFolder(folderId) { const arr = expandedFolderIds.value; const idx = arr.indexOf(folderId); @@ -488,7 +497,7 @@ onBeforeUnmount(() => { -
+
{{ actor.name }}
diff --git a/frontend/app/components/viewer/map/MapViewerPane.vue b/frontend/app/components/viewer/map/MapViewerPane.vue index d6ebf6b6..65faf0de 100644 --- a/frontend/app/components/viewer/map/MapViewerPane.vue +++ b/frontend/app/components/viewer/map/MapViewerPane.vue @@ -4,6 +4,7 @@ import { useI18n } from 'vue-i18n'; import { ClearWindow, CreateWindow, GetFirstWindowId } from '@/services/Windows'; import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu'; import { BuildNoteOptions, OptionLabel, ToImagePoint, ToScreenPoint } from '~/services/MapPins'; +import { ActorDragId, CellCentre, IsActorDrag, MoveByCells, TokenSize } from '~/services/MapTokens'; import { DisplayToast } from '~/services/Toaster'; import Server, { getBaseUrl } from '~/services/Server'; import { emitter } from '~/services/Emitter'; @@ -227,27 +228,29 @@ function onPinContextMenu(pin) { } async function savePin(noteId, spot) { - await updatePins('/map/pin', { id: map.value?._id, note: noteId, x: spot.x, y: spot.y }); + await updateMap('/map/pin', { id: map.value?._id, note: noteId, x: spot.x, y: spot.y }, t('campaigns.map.pins.error')); } async function removePin(pin) { - await updatePins('/map/unpin', { id: map.value?._id, pin: pin?._id }); + await updateMap('/map/unpin', { id: map.value?._id, pin: pin?._id }, t('campaigns.map.pins.error')); } -// 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; +// Every pin and token change answers with the whole map, which keeps the sidebar entry and the +// anchored map in step with what is on screen. +async function updateMap(route, body, failure) { + if (!body.id) return false; try { const response = await Server().post(route, body); if (response.data.status !== 'ok') { - DisplayToast('red', t('campaigns.map.pins.error'), 3000); - return; + DisplayToast('red', failure, 3000); + return false; } map.value = { ...response.data.map }; emitter.emit('campaign-entry-updated', { entityType: 'map', entry: response.data.map }); + return true; } catch (error) { - DisplayToast('red', t('campaigns.map.pins.error'), 3000); + DisplayToast('red', failure, 3000); + return false; } } @@ -274,27 +277,252 @@ function handlePinnedNoteRenamed({ key, title }) { option.label = OptionLabel(option); } +// --- Actors standing on the map as tokens --- +// An actor dragged out of the sidebar lands on the cell it is dropped on, and its token can then be +// dragged (or nudged with the arrow keys) from cell to cell. Tokens are kept in image pixels like the +// pins, so moving one only writes the middle of the cell it moved to. + +const actors = ref([]); +const actorsById = computed(() => new Map(actors.value.map((actor) => [String(actor._id), actor]))); +// Actor portraits that will not load (a Foundry path, say) fall back to the initials of the actor. +const brokenImages = ref(new Set()); +const draggingActor = ref(false); +// The token a pointer is holding, and the cell centre it is held at: the move stays local until the +// pointer lets go, so a drag across the map is one save and not one per mouse move. +const movingToken = ref(null); + +const grid = computed(() => ({ + gridSize: map.value?.gridSize, + offsetX: map.value?.offsetX, + offsetY: map.value?.offsetY +})); + +const tokens = computed(() => map.value?.tokens ?? []); + +// The actor names and portraits the tokens are drawn from. An actor that is not (or no longer) in the +// campaign is not dropped from the map here: the backend does that, and the next read of the map is +// the one that shows it gone. +async function fetchTokenActors() { + if (!campaignId.value) { + actors.value = []; + return; + } + try { + const response = await Server().get('/actor/list', { params: { campaign: campaignId.value } }); + actors.value = response.data.status === 'ok' ? (response.data.actors ?? []) : []; + } catch (error) { + actors.value = []; + } +} + +function tokenActor(token) { + return actorsById.value.get(String(token?.actor)) ?? null; +} + +function tokenLabel(token) { + return tokenActor(token)?.name ?? ''; +} + +function tokenInitials(token) { + const name = String(tokenLabel(token) ?? '').trim(); + if (!name) return '?'; + return name.split(/\s+/).slice(0, 2).map((part) => part.charAt(0).toUpperCase()).join(''); +} + +function tokenImage(token) { + const image = tokenActor(token)?.image; + if (!image || brokenImages.value.has(String(token?.actor))) return ''; + return /^(https?:|data:|\/\/)/i.test(image) ? image : `${getBaseUrl()}/public/${image}`; +} + +function onTokenImageError(token) { + brokenImages.value = new Set(brokenImages.value).add(String(token?.actor)); +} + +// Tokens are drawn in screen space too, but they are sized by the cell they stand on: unlike a pin, a +// token covers ground, so it grows and shrinks with the map. +function tokenStyle(token) { + const held = movingToken.value && String(movingToken.value.token?._id) === String(token?._id) + ? movingToken.value + : token; + const point = ToScreenPoint(held, viewState()); + const size = TokenSize(grid.value, zoom.value); + return { + left: `${point.x}px`, + top: `${point.y}px`, + width: `${size}px`, + height: `${size}px`, + // The initials of an actor with no portrait are read at the size of its token. + fontSize: `${Math.min(18, Math.max(9, Math.round(size * 0.36)))}px` + }; +} + +// The spot of the viewport a drop or a drag is over, in image pixels, or null outside of the image. +function imagePointOf(event) { + const bounds = viewport.value?.getBoundingClientRect(); + if (!bounds) return null; + return ToImagePoint({ x: event.clientX - bounds.left, y: event.clientY - bounds.top }, viewState()); +} + +function onMapDragOver(event) { + if (!imageUrl.value || !IsActorDrag(event)) return; + // Saying so is what lets the browser deliver the drop at all. + event.preventDefault(); + draggingActor.value = true; +} + +function onMapDragLeave(event) { + // Crossing into a child of the viewport is not leaving it. + if (event.relatedTarget && viewport.value?.contains(event.relatedTarget)) return; + draggingActor.value = false; +} + +async function onMapDrop(event) { + draggingActor.value = false; + const actorId = ActorDragId(event); + if (!actorId || !imageUrl.value || !map.value?._id) return; + + const spot = imagePointOf(event); + if (!spot) return; + await placeToken(actorId, spot); +} + +// An actor stands on the map once: dropping it again on a map it already occupies moves it there, the +// same way re-pinning a note moves its marker. +async function placeToken(actorId, spot) { + const centre = CellCentre(spot, grid.value); + if (!centre) return false; + return updateMap('/map/place-token', { + id: map.value?._id, actor: actorId, x: centre.x, y: centre.y + }, t('campaigns.map.tokens.error')); +} + +async function removeToken(token) { + await updateMap('/map/remove-token', { id: map.value?._id, token: token?._id }, t('campaigns.map.tokens.error')); +} + +let tokenPointerId = null; + +function onTokenPointerDown(event, token) { + // The token is what is being held here: the map must not start panning under the pointer. + event.stopPropagation(); + if (event.button !== 0) return; + + tokenPointerId = event.pointerId; + event.currentTarget.setPointerCapture?.(event.pointerId); + movingToken.value = { token: { ...token }, x: Number(token.x) || 0, y: Number(token.y) || 0 }; +} + +function onTokenPointerMove(event) { + if (!movingToken.value || event.pointerId !== tokenPointerId) return; + + const spot = imagePointOf(event); + // Dragged off the image, the token keeps the cell it had: an actor is never lost over the edge. + if (!spot) return; + const centre = CellCentre(spot, grid.value); + if (!centre) return; + movingToken.value = { ...movingToken.value, x: centre.x, y: centre.y }; +} + +async function onTokenPointerUp(event) { + if (!movingToken.value || event.pointerId !== tokenPointerId) return; + + const { token, x, y } = movingToken.value; + tokenPointerId = null; + movingToken.value = null; + event.currentTarget?.releasePointerCapture?.(event.pointerId); + + if (x === Number(token.x) && y === Number(token.y)) return; + await placeToken(token.actor, { x, y }); +} + +const CELL_STEPS = { + ArrowLeft: [-1, 0], + ArrowRight: [1, 0], + ArrowUp: [0, -1], + ArrowDown: [0, 1] +}; + +// A focused token answers to the keyboard too: arrows walk it over the grid, Delete takes it off. +async function onTokenKeydown(event, token) { + const step = CELL_STEPS[event.key]; + if (step) { + event.preventDefault(); + const centre = MoveByCells(token, grid.value, step[0], step[1]); + if (centre) await placeToken(token.actor, centre); + return; + } + if (event.key === 'Delete' || event.key === 'Backspace') { + event.preventDefault(); + await removeToken(token); + } +} + +function onTokenContextMenu(token) { + const actor = tokenActor(token); + const menuItems = []; + + if (actor) { + menuItems.push({ + name: t('campaigns.map.tokens.open'), + icon: '/icons/iconoir/regular/user.svg', + action: () => { HideContextMenu(); openActorSheet(actor); } + }); + menuItems.push({ divider: true }); + } + + menuItems.push({ + name: t('campaigns.map.tokens.remove'), + icon: '/icons/iconoir/regular/xmark-circle.svg', + action: () => { HideContextMenu(); removeToken(token); } + }); + ShowContextMenu(menuItems); +} + +async function openActorSheet(actor) { + // One sheet at a time, like the sidebar opens it. + const existingWindowId = GetFirstWindowId('character_sheet'); + if (existingWindowId !== undefined) ClearWindow({ id: existingWindowId }); + await nextTick(); + CreateWindow('character_sheet', { actor }); +} + +function handleActorEntry({ entityType, entry }) { + if (entityType !== 'actor' || !entry?._id) return; + if (entry.campaign && String(entry.campaign) !== String(campaignId.value)) return; + actors.value = [entry, ...actors.value.filter((current) => String(current._id) !== String(entry._id))]; +} + // A different map was anchored while this pane was already mounted. watch(() => props.map, (incoming, previous) => { if (incoming === previous) return; map.value = incoming ? { ...incoming } : null; imageSize.value = { width: 0, height: 0 }; + movingToken.value = null; + draggingActor.value = false; }); watch(campaignId, () => { noteOptions.value = []; fetchPinnableNotes(); + actors.value = []; + fetchTokenActors(); }); onMounted(() => { emitter.on('campaign-entry-updated', handleMapUpdated); + emitter.on('campaign-entry-created', handleActorEntry); + emitter.on('campaign-entry-updated', handleActorEntry); emitter.on('delete-note', handlePinnedNoteDeleted); emitter.on('title-updated', handlePinnedNoteRenamed); fetchPinnableNotes(); + fetchTokenActors(); }); onBeforeUnmount(() => { emitter.off('campaign-entry-updated', handleMapUpdated); + emitter.off('campaign-entry-created', handleActorEntry); + emitter.off('campaign-entry-updated', handleActorEntry); emitter.off('delete-note', handlePinnedNoteDeleted); emitter.off('title-updated', handlePinnedNoteRenamed); }); @@ -342,6 +570,9 @@ onBeforeUnmount(() => { @pointerup="onPointerUp" @pointercancel="onPointerUp" @contextmenu.prevent="onMapContextMenu" + @dragover="onMapDragOver" + @dragleave="onMapDragLeave" + @drop.prevent="onMapDrop" >
{{ $t('campaigns.map.no-image') }} @@ -404,6 +659,35 @@ onBeforeUnmount(() => { /* 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; } +/* Tokens are the actors standing on the map: drawn in screen space like the pins, but sized by the + grid cell they occupy, so a token covers its square whatever the zoom is (see TokenSize). */ +.map-tokens { position: absolute; inset: 0; pointer-events: none; } +.map-token { + position: absolute; transform: translate(-50%, -50%); pointer-events: auto; + display: flex; align-items: center; justify-content: center; margin: 0; padding: 0; + border: 2px solid var(--color-link); border-radius: 50%; + background: var(--color-background-soft); color: var(--color-text); + cursor: grab; user-select: none; box-shadow: 0px 0px 6px -1px rgba(0,0,0,0.55); +} +.map-token:hover { border-color: var(--color-text); } +.map-token:focus-visible { outline: 1px solid var(--color-link); outline-offset: 2px; } +.map-token.moving { cursor: grabbing; } +.token-image { position: absolute; inset: 0; box-sizing: border-box; width: 100%; height: 100%; object-fit: cover; border-radius: 50%; } +/* No portrait (or one that will not load): the token shows the initials of its actor instead. */ +.token-initials { opacity: .8; white-space: nowrap; } +.token-label { + display: none; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); margin-top: 3px; + max-width: 160px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + font-size: 11px; text-shadow: 0px 0px 4px rgba(0,0,0,0.8); +} +.map-token:hover .token-label, .map-token:focus-visible .token-label { display: block; } +/* Shown while an actor is carried over the map from the sidebar, so the spot to let go of it has. */ +.map-drop-hint { + position: absolute; top: 10px; left: 50%; transform: translateX(-50%); + padding: 5px 10px; border: 1px dashed var(--color-link); border-radius: 7px; + background: var(--color-background-soft); color: var(--color-text); font-size: 12px; + pointer-events: none; box-shadow: 0px 0px 6px -1px rgba(0,0,0,0.55); +} .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/services/MapTokens.js b/frontend/app/services/MapTokens.js new file mode 100644 index 00000000..31dbd1f2 --- /dev/null +++ b/frontend/app/services/MapTokens.js @@ -0,0 +1,69 @@ +// The rules behind the actor tokens of a map (drag an actor from the sidebar onto a map, move the +// token from cell to cell). Like the pins, a token is stored in image pixels, so these helpers only +// translate and snap: they hold no state and talk to no API. + +// What the sidebar puts into a drag when an actor row is pulled out of it, so the map knows an actor +// is on its way and nothing else dropped on it (a note, a file) is taken for one. +const ACTOR_DRAG_TYPE = 'application/x-dragonroll-actor'; + +// The actor id carried by a drag event, or null when the drag carries no actor. `types` is what a +// dragover can see: the data itself is protected until the drop. +function IsActorDrag(event) { + return Array.from(event?.dataTransfer?.types ?? []).includes(ACTOR_DRAG_TYPE); +} + +function ActorDragId(event) { + return String(event?.dataTransfer?.getData?.(ACTOR_DRAG_TYPE) ?? '').trim() || null; +} + +// The middle of the grid cell a point of the image stands in, in image pixels: this is what a token +// is stored at, so it always stands in a square of the grid. The backend snaps the same way, so a +// token does not move when a drag lands. +function CellCentre(point, grid) { + const size = Math.max(1, Number(grid?.gridSize) || 50); + const offsetX = Number(grid?.offsetX) || 0; + const offsetY = Number(grid?.offsetY) || 0; + + const x = Number(point?.x); + const y = Number(point?.y); + if (!Number.isFinite(x) || !Number.isFinite(y)) return null; + + // Spots off the top left corner count from the corner itself, and only whole pixels count: both + // the way the route reads a coordinate, so the token a drag shows is the token that gets saved. + const column = Math.floor((Math.max(0, Math.round(x)) - offsetX) / size); + const row = Math.floor((Math.max(0, Math.round(y)) - offsetY) / size); + return { + x: Math.max(0, Math.round(offsetX + (column + 0.5) * size)), + y: Math.max(0, Math.round(offsetY + (row + 0.5) * size)) + }; +} + +// A token moved by whole cells (the arrow keys of a focused token): the same cell width the grid is +// drawn with, so a token steps from one square to the next and never in between. +function MoveByCells(centre, grid, columns, rows) { + const size = Math.max(1, Number(grid?.gridSize) || 50); + const x = Number(centre?.x); + const y = Number(centre?.y); + if (!Number.isFinite(x) || !Number.isFinite(y)) return null; + + return { + x: Math.max(0, Math.round(x + Number(columns) * size)), + y: Math.max(0, Math.round(y + Number(rows) * size)) + }; +} + +// The side of a token in screen pixels: one grid cell, so a token covers the square it stands in at +// every zoom. Never smaller than an icon, or a zoomed-out map would hide its actors. +function TokenSize(grid, zoom) { + const cell = Math.max(1, Number(grid?.gridSize) || 50) * (Number(zoom) || 1); + return Math.round(Math.max(18, cell)); +} + +export { + ACTOR_DRAG_TYPE, + ActorDragId, + CellCentre, + IsActorDrag, + MoveByCells, + TokenSize +}; diff --git a/frontend/i18n/locales/ca/campaigns.json b/frontend/i18n/locales/ca/campaigns.json index b85ca8b2..a2974330 100644 --- a/frontend/i18n/locales/ca/campaigns.json +++ b/frontend/i18n/locales/ca/campaigns.json @@ -84,6 +84,12 @@ "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." + }, + "tokens": { + "token": "Fitxa", "drag": "Arrossega aquest actor sobre un mapa per posar-lo", + "drop-hint": "Deixa anar per posar l'actor en aquest mapa", + "open": "Obre la fitxa de personatge", "remove": "Treu la fitxa", + "error": "No s'han pogut canviar les fitxes d'aquest mapa." } }, "character-sheet": { diff --git a/frontend/i18n/locales/en/campaigns.json b/frontend/i18n/locales/en/campaigns.json index e04a357f..a04baf4f 100644 --- a/frontend/i18n/locales/en/campaigns.json +++ b/frontend/i18n/locales/en/campaigns.json @@ -88,6 +88,12 @@ "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." + }, + "tokens": { + "token": "Token", "drag": "Drag this actor onto a map to place it there", + "drop-hint": "Drop to place the actor on this map", + "open": "Open character sheet", "remove": "Remove token", + "error": "Unable to change the tokens of this map." } }, "character-sheet": { diff --git a/frontend/i18n/locales/es/campaigns.json b/frontend/i18n/locales/es/campaigns.json index 89f97f94..8ed35b74 100644 --- a/frontend/i18n/locales/es/campaigns.json +++ b/frontend/i18n/locales/es/campaigns.json @@ -84,6 +84,12 @@ "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." + }, + "tokens": { + "token": "Ficha", "drag": "Arrastra este actor sobre un mapa para colocarlo", + "drop-hint": "Suelta para colocar al actor en este mapa", + "open": "Abrir hoja de personaje", "remove": "Quitar la ficha", + "error": "No se pudieron cambiar las fichas de este mapa." } }, "character-sheet": { diff --git a/tests/map-pins.test.js b/tests/map-pins.test.js index 1e466502..91bcce40 100644 --- a/tests/map-pins.test.js +++ b/tests/map-pins.test.js @@ -83,6 +83,8 @@ function loadMapRoutes({ ownsCampaign = true, maps = [], notes = [] } = {}) { : null ), }, + // The pins do not ask after actors, only the token routes below do. + "../models/Actor": { findOne: () => mongooseQuery(null) }, }); } diff --git a/tests/map-tokens.test.js b/tests/map-tokens.test.js new file mode 100644 index 00000000..9bbe5631 --- /dev/null +++ b/tests/map-tokens.test.js @@ -0,0 +1,344 @@ +// Tests for the actor tokens of a map (Syndria98/dragonroll#38): an actor dragged out of the campaign +// sidebar lands on the map as a token, and that token is then moved from cell to cell of the grid. +// +// Same set-up as tests/map-pins.test.js, which the repository root runs without installing anything: +// the express routers are loaded into `node:vm` with their models stubbed, `MapTokens.js` is loaded as +// a plain function, and the last checks read the templates, where the drag and drop 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. +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]; + }; + + 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; } }; + await handlers[handlers.length - 1]({ body, query, params, user }, res); + return res.payload; + } + + return { routes, call }; +} + +function makeMap(tokens = [], grid = {}) { + return { + _id: "map-1", campaign: "campaign-1", tokens, + gridSize: 50, offsetX: 0, offsetY: 0, + ...grid, + save: async () => {} + }; +} + +function loadMapRoutes({ ownsCampaign = true, maps = [], actors = [] } = {}) { + 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: () => mongooseQuery(null) }, + "../models/Actor": { + findOne: (filter) => mongooseQuery( + actors.some((actor) => actor._id === String(filter._id) && String(actor.campaign) === String(filter.campaign)) + ? { _id: String(filter._id) } + : null + ), + }, + }); +} + +function placeTokenRouteTests() { + test("an actor dropped on the map stands in the middle of the cell it landed on", async () => { + const map = makeMap(); + const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] }); + + const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 124, y: 76 } }); + + assert.equal(response.status, "ok"); + // 50 px cells: 124 falls in the column centred on 125, 76 in the row centred on 75. + assert.deepEqual(map.tokens, [{ actor: "actor-1", x: 125, y: 75 }]); + }); + + test("a token lands in the cell of a grid that does not start at the corner of the image", async () => { + const map = makeMap([], { gridSize: 40, offsetX: 10, offsetY: 4 }); + const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] }); + + await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 55, y: 20 } }); + + assert.deepEqual(map.tokens, [{ actor: "actor-1", x: 70, y: 24 }]); + }); + + test("an actor of another campaign cannot be made to stand on a map", async () => { + const map = makeMap(); + const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-2", campaign: "campaign-2" }] }); + + const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-2", x: 10, y: 10 } }); + + assert.equal(response.msg, "errors.notfound"); + assert.deepEqual(map.tokens, []); + }); + + test("a map of somebody else's campaign answers unauthorized", async () => { + const map = makeMap(); + const api = loadMapRoutes({ ownsCampaign: false, maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] }); + + const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 10, y: 10 } }); + + assert.equal(response.msg, "unauthorized"); + assert.deepEqual(map.tokens, []); + }); + + test("placing an actor again moves its token instead of adding a twin", async () => { + const map = makeMap([{ _id: "token-1", actor: "actor-1", x: 25, y: 25 }]); + const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] }); + + await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 300, y: 224 } }); + + assert.equal(map.tokens.length, 1); + assert.deepEqual({ ...map.tokens[0] }, { _id: "token-1", actor: "actor-1", x: 325, y: 225 }); + }); + + test("placing a token needs both a map and an actor", async () => { + const map = makeMap(); + const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] }); + + assert.equal((await api.call("POST /place-token", { body: { actor: "actor-1", x: 1, y: 1 } })).msg, "errors.missing-data"); + assert.equal((await api.call("POST /place-token", { body: { id: "map-1", x: 1, y: 1 } })).msg, "errors.missing-data"); + assert.deepEqual(map.tokens, []); + }); + + test("removing a token takes the one it is given and keeps the others", async () => { + const map = makeMap([ + { _id: "token-1", actor: "actor-1", x: 25, y: 25 }, + { _id: "token-2", actor: "actor-2", x: 75, y: 25 }, + ]); + const api = loadMapRoutes({ maps: [map] }); + + const response = await api.call("POST /remove-token", { body: { id: "map-1", token: "token-1" } }); + + assert.equal(response.status, "ok"); + assert.deepEqual(map.tokens.map((token) => token._id), ["token-2"]); + }); + + test("removing a token of a map of somebody else keeps its tokens", async () => { + const map = makeMap([{ _id: "token-1", actor: "actor-1", x: 25, y: 25 }]); + const api = loadMapRoutes({ ownsCampaign: false, maps: [map] }); + + const response = await api.call("POST /remove-token", { body: { id: "map-1", token: "token-1" } }); + + assert.equal(response.msg, "unauthorized"); + assert.equal(map.tokens.length, 1); + }); +} + +function loadActorRoutes({ ownsCampaign = true, actors = [], deletedCount = 1 } = {}) { + const tokensPulled = []; + const api = loadRouter(["backend", "src", "routes", "actor.js"], { + "../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) }, + "../models/Actor": { + findById: (id) => mongooseQuery( + actors.find((actor) => actor._id === id) + ? { ...actors.find((actor) => actor._id === id), deleteOne: async () => ({ deletedCount }) } + : null + ), + }, + "../models/Map": { + // The driver drops the tokens of the actor from every map holding one; what is worth + // keeping here is the filter it is asked to do that with. + updateMany: async (filter, update) => { + tokensPulled.push({ filter, update }); + return { modifiedCount: 1 }; + }, + }, + }); + return { api, tokensPulled }; +} + +function actorDeletionTests() { + test("deleting an actor takes its tokens off the maps", async () => { + const { api, tokensPulled } = loadActorRoutes({ actors: [{ _id: "actor-1", campaign: "campaign-1" }] }); + + const response = await api.call("POST /delete", { body: { id: "actor-1" } }); + + assert.equal(response.status, "ok"); + assert.deepEqual(tokensPulled, [{ filter: { "tokens.actor": "actor-1" }, update: { $pull: { tokens: { actor: "actor-1" } } } }]); + }); + + test("a token is not left behind by an actor that could not be deleted", async () => { + const { api, tokensPulled } = loadActorRoutes({ ownsCampaign: false, actors: [{ _id: "actor-1", campaign: "campaign-1" }] }); + + const response = await api.call("POST /delete", { body: { id: "actor-1" } }); + + assert.equal(response.msg, "unauthorized"); + assert.deepEqual(tokensPulled, []); + }); +} + +function loadMapTokensService() { + const source = readRepoFile("frontend", "app", "services", "MapTokens.js"); + const body = source + .replace(/import\s*\{[^}]*\}\s*from\s*['"]vue['"];?/, "") + .replace(/export\s*\{/, "return {") + .concat("\n;"); + + return vm.compileFunction(body, [])(); +} + +function mapTokensServiceTests() { + const service = loadMapTokensService(); + const grid = { gridSize: 50, offsetX: 0, offsetY: 0 }; + + test("a spot of the image becomes the middle of the cell it stands in", () => { + assert.deepEqual(service.CellCentre({ x: 124, y: 76 }, grid), { x: 125, y: 75 }); + assert.deepEqual(service.CellCentre({ x: 125, y: 75 }, grid), { x: 125, y: 75 }); + }); + + test("cells are counted from the grid origin, not from the corner of the image", () => { + const shifted = { gridSize: 40, offsetX: 10, offsetY: 4 }; + assert.deepEqual(service.CellCentre({ x: 55, y: 20 }, shifted), { x: 70, y: 24 }); + }); + + test("a token never stands off the top left corner of the map", () => { + assert.deepEqual(service.CellCentre({ x: -8, y: -1 }, grid), { x: 25, y: 25 }); + // A grid starting off the image still cannot put a token at a negative pixel. + assert.deepEqual(service.CellCentre({ x: -8, y: -1 }, { gridSize: 40, offsetX: -30, offsetY: 0 }), { x: 0, y: 20 }); + }); + + test("a grid with nothing set is the 50 px grid the backend defaults to", () => { + assert.deepEqual(service.CellCentre({ x: 10, y: 10 }, {}), { x: 25, y: 25 }); + assert.deepEqual(service.CellCentre({ x: 10, y: 10 }, undefined), { x: 25, y: 25 }); + }); + + test("a spot that is not a spot centres on nothing", () => { + assert.equal(service.CellCentre({ x: NaN, y: 10 }, grid), null); + assert.equal(service.CellCentre({}, grid), null); + assert.equal(service.CellCentre(undefined, grid), null); + }); + + test("the arrow keys walk a token over whole cells", () => { + assert.deepEqual(service.MoveByCells({ x: 125, y: 75 }, grid, -1, 2), { x: 75, y: 175 }); + assert.deepEqual(service.MoveByCells({ x: 25, y: 25 }, grid, -3, -1), { x: 0, y: 0 }); + assert.equal(service.MoveByCells({ x: 25 }, grid, 1, 0), null); + }); + + test("a token covers the cell it stands on and never shrinks below an icon", () => { + assert.equal(service.TokenSize(grid, 1), 50); + assert.equal(service.TokenSize(grid, 0.2), 18); + assert.equal(service.TokenSize({ gridSize: 80 }, 2), 160); + }); + + test("the map tells an actor drag from any other drag dropped on it", () => { + const actorDrag = { + dataTransfer: { + types: [service.ACTOR_DRAG_TYPE], + getData: (type) => (type === service.ACTOR_DRAG_TYPE ? "actor-1" : "") + } + }; + const noteDrag = { dataTransfer: { types: ["text/plain"], getData: (type) => (type === "text/plain" ? "note-1" : "") } }; + + assert.equal(service.IsActorDrag(actorDrag), true); + assert.equal(service.ActorDragId(actorDrag), "actor-1"); + assert.equal(service.IsActorDrag(noteDrag), false); + assert.equal(service.ActorDragId(noteDrag), null); + assert.equal(service.IsActorDrag(undefined), false); + assert.equal(service.ActorDragId(undefined), null); + }); + + test("the viewer and the route agree on where a token stands", async () => { + // A drop is snapped while it is dragged and again when it is saved: the token must not jump. + const map = makeMap([], { gridSize: 40, offsetX: 10, offsetY: 4 }); + const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] }); + + const spot = { x: 300, y: 220 }; + await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", ...spot } }); + + assert.deepEqual({ x: map.tokens[0].x, y: map.tokens[0].y }, service.CellCentre(spot, map)); + }); +} + +function mapViewerTokenWiringTests() { + const pane = readRepoFile("frontend", "app", "components", "viewer", "map", "MapViewerPane.vue"); + const sidebar = readRepoFile("frontend", "app", "components", "partials", "ContentSidebar.vue"); + + test("an actor row of the sidebar can be dragged out of it", () => { + const actorRow = /
]*>/.exec(sidebar)?.[0]; + assert.ok(actorRow, "expected the actor rows of the sidebar"); + assert.match(actorRow, /draggable="true"/); + assert.match(actorRow, /@dragstart="startActorDrag\(\$event, actor\)"/); + assert.match(sidebar, /setData\(ACTOR_DRAG_TYPE, String\(actor\._id\)\)/); + }); + + test("the map viewport takes the actor drag and places it", () => { + const viewport = /]*ref="viewport"[\s\S]*?>/.exec(pane)?.[0]; + assert.ok(viewport, "expected the map viewport element"); + assert.match(viewport, /@dragover="onMapDragOver"/); + assert.match(viewport, /@drop\.prevent="onMapDrop"/); + }); + + test("tokens are drawn in screen space, sized by their cell, and only they catch the mouse", () => { + assert.match(pane, /class="map-token"[^>]*:style="tokenStyle\(token\)"/); + assert.match(pane, /\.map-tokens\s*\{[^}]*pointer-events:\s*none/); + assert.match(pane, /\.map-token\s*\{[^}]*pointer-events:\s*auto/); + }); + + test("dragging a token moves it and does not pan the map", () => { + assert.match(pane, /@pointerdown="onTokenPointerDown\(\$event, token\)"/); + assert.match(pane, /@pointermove="onTokenPointerMove"/); + assert.match(pane, /@pointerup="onTokenPointerUp"/); + // The pane stops the pointer before the viewport ever sees it, so holding a token never pans. + assert.match(pane, /function onTokenPointerDown\(event, token\) \{[^}]*?event\.stopPropagation\(\)/); + }); + + test("a token answers to the keyboard and its own menu", () => { + assert.match(pane, /@keydown="onTokenKeydown\(\$event, token\)"/); + assert.match(pane, /@contextmenu\.stop\.prevent="onTokenContextMenu\(token\)"/); + }); + + test("tokens are saved and taken off through the map routes", () => { + assert.match(pane, /['"]\/map\/place-token['"]/); + assert.match(pane, /['"]\/map\/remove-token['"]/); + }); +} + +placeTokenRouteTests(); +actorDeletionTests(); +mapTokensServiceTests(); +mapViewerTokenWiringTests(); -- 2.39.5