Files
dragonroll/frontend/app/components/viewer/map/MapViewerPane.vue
Gitea OpenCode Agent 3c3df58d8d
Some checks failed
Test / test (push) Failing after 2s
Fix issue #100: Add walls to maps
2026-10-16 00:59:56 +00:00

1011 lines
45 KiB
Vue

<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
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 { IsWall, MoveWall, SnapToGrid, ToDrawPoint, ToScreenWall } from '~/services/MapWalls';
import { DisplayToast } from '~/services/Toaster';
import Server, { getBaseUrl } from '~/services/Server';
import { emitter } from '~/services/Emitter';
import { useCampaignService } from '~/services/Campaign.js';
// The map viewer without window chrome: it fills whatever flex column holds it, so the same
// component works inside MapViewerWindow.vue and anchored on the campaign content area.
const props = defineProps({
map: { type: Object, default: null },
// Anchored maps can be detached into a floating window; the window itself does not offer it.
anchored: { type: Boolean, default: false }
});
const emit = defineEmits(['detach']);
const { Campaign } = useCampaignService();
const campaignId = computed(() => Campaign.value?._id ?? Campaign.value?.id ?? null);
const map = ref(props.map ? { ...props.map } : null);
const viewport = ref(null);
const zoom = ref(1);
const pan = ref({ x: 0, y: 0 });
const imageSize = ref({ width: 0, height: 0 });
const showGrid = ref(true);
const dragging = ref(false);
const minZoom = 0.05;
const maxZoom = 8;
const imageUrl = computed(() => {
const image = map.value?.image;
if (!image) return '';
return /^(https?:|data:|\/\/)/i.test(image) ? image : `${getBaseUrl()}/public/${image}`;
});
const stageStyle = computed(() => ({
transform: `translate3d(${pan.value.x}px, ${pan.value.y}px, 0) scale(${zoom.value})`
}));
// The grid is drawn in screen space over the image so its lines stay one pixel wide at any zoom.
const gridStyle = computed(() => {
if (!showGrid.value || !imageSize.value.width) return { display: 'none' };
const cell = `${Math.max(1, Number(map.value?.gridSize) || 50) * zoom.value}px`;
return {
width: `${imageSize.value.width * zoom.value}px`,
height: `${imageSize.value.height * zoom.value}px`,
transform: `translate3d(${pan.value.x + (Number(map.value?.offsetX) || 0) * zoom.value}px, ${pan.value.y + (Number(map.value?.offsetY) || 0) * zoom.value}px, 0)`,
backgroundImage: `linear-gradient(to right, var(--color-link) 1px, transparent 1px), linear-gradient(to bottom, var(--color-link) 1px, transparent 1px)`,
backgroundSize: `${cell} ${cell}`
};
});
const zoomPercent = computed(() => `${Math.round(zoom.value * 100)}%`);
function clampZoom(value) {
if (!Number.isFinite(value)) return minZoom;
return Math.min(maxZoom, Math.max(minZoom, value));
}
function fitToWindow() {
const bounds = viewport.value?.getBoundingClientRect();
if (!bounds || !imageSize.value.width) return;
zoom.value = clampZoom(Math.min(bounds.width / imageSize.value.width, bounds.height / imageSize.value.height));
centerOn();
}
function centerOn() {
const bounds = viewport.value?.getBoundingClientRect();
if (!bounds || !imageSize.value.width) return;
pan.value = {
x: (bounds.width - imageSize.value.width * zoom.value) / 2,
y: (bounds.height - imageSize.value.height * zoom.value) / 2
};
}
function onImageLoaded(event) {
imageSize.value = { width: event.target.naturalWidth, height: event.target.naturalHeight };
fitToWindow();
}
// Zoom keeping the map point under `point` where it is.
function zoomAt(factor, point) {
const next = clampZoom(zoom.value * factor);
if (next === zoom.value) return;
const ratio = next / zoom.value;
pan.value = {
x: point.x - (point.x - pan.value.x) * ratio,
y: point.y - (point.y - pan.value.y) * ratio
};
zoom.value = next;
}
function onWheel(event) {
const bounds = viewport.value?.getBoundingClientRect();
if (!bounds) return;
zoomAt(event.deltaY < 0 ? 1.15 : 1 / 1.15, { x: event.clientX - bounds.left, y: event.clientY - bounds.top });
}
function zoomFromToolbar(incoming) {
const bounds = viewport.value?.getBoundingClientRect();
if (!bounds) return;
zoomAt(incoming ? 1.25 : 1 / 1.25, { x: bounds.width / 2, y: bounds.height / 2 });
}
let pointerId = null;
let lastPointer = { x: 0, y: 0 };
function onPointerDown(event) {
if (event.button !== 0 || !viewport.value) return;
if (editingWalls.value && imageUrl.value) {
// While the wall editor is open the left pointer draws instead of panning: the wheel and
// the zoom buttons still move the view about.
const spot = wallSpot(event);
const first = spot && SnapToGrid(spot, grid.value);
if (!first) return;
pointerId = event.pointerId;
viewport.value.setPointerCapture?.(event.pointerId);
drawingWall.value = { x1: first.x, y1: first.y, x2: first.x, y2: first.y };
selectedWall.value = null;
return;
}
dragging.value = true;
pointerId = event.pointerId;
lastPointer = { x: event.clientX, y: event.clientY };
viewport.value.setPointerCapture?.(event.pointerId);
}
function onPointerMove(event) {
if (drawingWall.value && event.pointerId === pointerId) {
const spot = wallSpot(event);
const snapped = spot && SnapToGrid(spot, grid.value);
if (snapped) drawingWall.value = { ...drawingWall.value, x2: snapped.x, y2: snapped.y };
return;
}
if (!dragging.value || event.pointerId !== pointerId) return;
pan.value = { x: pan.value.x + (event.clientX - lastPointer.x), y: pan.value.y + (event.clientY - lastPointer.y) };
lastPointer = { x: event.clientX, y: event.clientY };
}
async function onPointerUp(event) {
if (event.pointerId !== pointerId) return;
if (drawingWall.value) {
const segment = drawingWall.value;
pointerId = null;
drawingWall.value = null;
viewport.value?.releasePointerCapture?.(event.pointerId);
// A drag that ended where it started drew no wall; anything with length becomes one.
if (IsWall(segment)) await saveWalls([...walls.value, segment]);
return;
}
dragging.value = false;
pointerId = null;
viewport.value?.releasePointerCapture?.(event.pointerId);
}
function editMap() {
if (!map.value || !campaignId.value) return;
CreateWindow('create_map', { campaign: campaignId.value, entry: map.value });
}
function handleMapUpdated({ entityType, entry }) {
if (entityType !== 'map' || entry?._id !== map.value?._id) return;
const imageChanged = entry.image !== map.value.image;
map.value = { ...entry };
// A new image is fitted again by onImageLoaded; grid-only changes just move the overlay.
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 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 updateMap('/map/unpin', { id: map.value?._id, pin: pin?._id }, t('campaigns.map.pins.error'));
}
// 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', 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', failure, 3000);
return false;
}
}
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);
}
// --- 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 });
}
// Double clicking a token (or Enter on a focused one) opens the sheet of the actor it stands for.
// A single click cannot be the trigger: the click that ends a drag lands on the token too, so
// dragging a token over the map would open its sheet every time.
function openTokenSheet(token) {
const actor = tokenActor(token);
if (actor) openActorSheet(actor);
}
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
// and Enter opens its sheet, the way a double click does.
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);
}
if (event.key === 'Enter') openTokenSheet(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))];
}
// --- Walls blocking the map ---
// The wall editor: with walls on, dragging over the map draws a segment from one grid intersection
// to the next, dragging an endpoint retypes it, dragging the segment itself moves it, and right
// clicking one (or Delete on a focused one) opens its controls and takes it off. Walls are stored
// in image pixels like the pins, and every edit saves the whole set — the same set a paired
// Foundry scene takes over, so the two see the same walls.
const walls = computed(() => map.value?.walls ?? []);
const editingWalls = ref(false);
// The wall a pointer is holding: a new segment being dragged, the whole segment being slid, or one
// endpoint being retyped. Like a token's move, the change stays local until the pointer lets go,
// so a drag across the map is one save and not one per mouse move.
const drawingWall = ref(null);
const draggingWall = ref(null);
const draggingEnd = ref(null);
// The wall whose controls are asked for: selected before its menu opens, kept while it is dragged.
const selectedWall = ref(null);
const END_KEYS = [['x1', 'y1'], ['x2', 'y2']];
let wallDragPointerId = null;
let lastWallDrag = { x: 0, y: 0 };
function toggleWallEditing() {
editingWalls.value = !editingWalls.value;
if (!editingWalls.value) {
drawingWall.value = null;
draggingWall.value = null;
draggingEnd.value = null;
selectedWall.value = null;
}
}
// The spot of the viewport in image pixels, clamped to the image: while a wall is being held the
// pointer may cross an edge, and the wall should stay on the map rather than vanish.
function wallSpot(event) {
const bounds = viewport.value?.getBoundingClientRect();
if (!bounds) return null;
return ToDrawPoint({ x: event.clientX - bounds.left, y: event.clientY - bounds.top }, viewState());
}
// The wall as it should be drawn right now: with the drag's preview on top of what is stored.
function wallGeometry(wall) {
if (draggingWall.value && String(draggingWall.value.wall?._id) === String(wall?._id)) {
const moved = MoveWall(wall, draggingWall.value.dx, draggingWall.value.dy);
if (moved) return { ...wall, ...moved };
}
if (draggingEnd.value && String(draggingEnd.value.wall?._id) === String(wall?._id) && draggingEnd.value.point) {
const [keyX, keyY] = END_KEYS[draggingEnd.value.end];
return { ...wall, [keyX]: draggingEnd.value.point.x, [keyY]: draggingEnd.value.point.y };
}
return wall;
}
function wallScreen(wall) {
return ToScreenWall(wallGeometry(wall), viewState());
}
function wallClasses(wall) {
return {
'wall-door': Number(wall?.door) > 0,
'wall-move-only': !wall?.sight && Number(wall?.door) === 0,
selected: Boolean(selectedWall.value) && String(selectedWall.value) === String(wall?._id)
};
}
// The wire shape of a wall: what the server keeps, with the `_id` of the ones it already has so a
// save neither doubles them nor re-ids them under the viewer's feet.
function plainWall(wall) {
const stored = {
x1: Number(wall.x1), y1: Number(wall.y1), x2: Number(wall.x2), y2: Number(wall.y2),
move: wall.move !== false, sight: wall.sight !== false, door: Number(wall.door) || 0
};
return wall._id ? { _id: String(wall._id), ...stored } : stored;
}
async function saveWalls(next) {
return updateMap('/map/walls', { id: map.value?._id, walls: next.map(plainWall) }, t('campaigns.map.walls.error'));
}
async function replaceWall(wall, patch) {
const next = walls.value.map((current) => (
String(current?._id) === String(wall?._id) ? { ...current, ...patch } : current
));
await saveWalls(next);
}
async function removeWall(wall) {
if (String(selectedWall.value) === String(wall?._id)) selectedWall.value = null;
await saveWalls(walls.value.filter((current) => String(current?._id) !== String(wall?._id)));
}
function onWallPointerDown(event, wall) {
// The segment is what is being held here: the map must not start panning under the pointer.
event.stopPropagation();
if (event.button !== 0) return;
wallDragPointerId = event.pointerId;
event.currentTarget.setPointerCapture?.(event.pointerId);
lastWallDrag = { x: event.clientX, y: event.clientY };
selectedWall.value = String(wall?._id ?? '');
draggingWall.value = { wall, dx: 0, dy: 0 };
}
function onWallPointerMove(event) {
if (!draggingWall.value || event.pointerId !== wallDragPointerId) return;
const zoomScale = zoom.value || 1;
draggingWall.value = {
...draggingWall.value,
// The drag is measured in screen pixels and applied in image ones, and the whole segment
// goes by the same delta: a moved wall keeps its shape and the grid it was drawn on.
dx: draggingWall.value.dx + (event.clientX - lastWallDrag.x) / zoomScale,
dy: draggingWall.value.dy + (event.clientY - lastWallDrag.y) / zoomScale
};
lastWallDrag = { x: event.clientX, y: event.clientY };
}
async function onWallPointerUp(event) {
if (!draggingWall.value || event.pointerId !== wallDragPointerId) return;
const { wall, dx, dy } = draggingWall.value;
wallDragPointerId = null;
draggingWall.value = null;
event.currentTarget?.releasePointerCapture?.(event.pointerId);
const moved = MoveWall(wall, dx, dy);
if (!moved || (moved.x1 === Number(wall.x1) && moved.y1 === Number(wall.y1)
&& moved.x2 === Number(wall.x2) && moved.y2 === Number(wall.y2))) return;
await replaceWall(wall, moved);
}
function onWallEndPointerDown(event, wall, end) {
event.stopPropagation();
if (event.button !== 0) return;
wallDragPointerId = event.pointerId;
event.currentTarget.setPointerCapture?.(event.pointerId);
selectedWall.value = String(wall?._id ?? '');
draggingEnd.value = { wall, end, point: { x: Number(wall[END_KEYS[end][0]]), y: Number(wall[END_KEYS[end][1]]) } };
}
function onWallEndPointerMove(event) {
if (!draggingEnd.value || event.pointerId !== wallDragPointerId) return;
const spot = wallSpot(event);
const snapped = spot && SnapToGrid(spot, grid.value);
if (!snapped) return;
draggingEnd.value = { ...draggingEnd.value, point: snapped };
}
async function onWallEndPointerUp(event) {
if (!draggingEnd.value || event.pointerId !== wallDragPointerId) return;
const { wall, end, point } = draggingEnd.value;
wallDragPointerId = null;
draggingEnd.value = null;
event.currentTarget?.releasePointerCapture?.(event.pointerId);
const [keyX, keyY] = END_KEYS[end];
if (point.x === Number(wall[keyX]) && point.y === Number(wall[keyY])) return;
const retyped = { ...wall, [keyX]: point.x, [keyY]: point.y };
// Retyped into its own end, the segment has no length left: the wall is gone.
if (!IsWall(retyped)) await removeWall(wall);
else await replaceWall(wall, { [keyX]: point.x, [keyY]: point.y });
}
function onWallContextMenu(wall) {
selectedWall.value = String(wall?._id ?? '');
ShowContextMenu([
{
name: t(wall.sight ? 'campaigns.map.walls.sight-open' : 'campaigns.map.walls.sight-block'),
icon: '/icons/iconoir/regular/eye.svg',
action: () => { HideContextMenu(); replaceWall(wall, { sight: !wall.sight }); }
},
{
name: t(wall.move ? 'campaigns.map.walls.move-open' : 'campaigns.map.walls.move-block'),
icon: '/icons/iconoir/regular/lock.svg',
action: () => { HideContextMenu(); replaceWall(wall, { move: !wall.move }); }
},
{
name: t('campaigns.map.walls.door'),
icon: '/icons/iconoir/regular/home-simple-door.svg',
context: [
{ name: t('campaigns.map.walls.door-none'), action: () => { HideContextMenu(); replaceWall(wall, { door: 0 }); } },
{ name: t('campaigns.map.walls.door-closed'), action: () => { HideContextMenu(); replaceWall(wall, { door: 2 }); } },
{ name: t('campaigns.map.walls.door-open'), action: () => { HideContextMenu(); replaceWall(wall, { door: 1 }); } }
]
},
{ divider: true },
{
name: t('campaigns.map.walls.remove'),
icon: '/icons/iconoir/regular/xmark-circle.svg',
action: () => { HideContextMenu(); removeWall(wall); }
}
]);
}
// A focused wall answers Delete too, the way a focused token does.
async function onWallKeydown(event, wall) {
if (event.key !== 'Delete' && event.key !== 'Backspace') return;
event.preventDefault();
await removeWall(wall);
}
// Escape lets go of whatever the editor is holding: an unfinished segment first, the selection next.
function onWindowKeydown(event) {
if (event.key !== 'Escape') return;
if (drawingWall.value) drawingWall.value = null;
else if (selectedWall.value) selectedWall.value = null;
}
// 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;
drawingWall.value = null;
draggingWall.value = null;
draggingEnd.value = null;
selectedWall.value = null;
});
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);
window.addEventListener('keydown', onWindowKeydown);
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);
window.removeEventListener('keydown', onWindowKeydown);
});
</script>
<template>
<div class="map-pane">
<div class="viewer-bar">
<div class="viewer-identity">
<strong>{{ map?.name }}</strong>
<span class="viewer-meta">{{ $t('campaigns.map.summary', { size: map?.gridSize, scale: map?.scale }) }}</span>
</div>
<div class="viewer-tools">
<button class="viewer-tool" :class="{ selected: showGrid }" type="button" :title="$t('campaigns.map.toggle-grid')"
:aria-label="$t('campaigns.map.toggle-grid')" :aria-pressed="showGrid.toString()" @click="showGrid = !showGrid">
<img class="tool-icon" src="/icons/iconoir/regular/view-grid.svg" alt="" aria-hidden="true">
</button>
<button class="viewer-tool" :class="{ selected: editingWalls }" type="button" :title="$t('campaigns.map.walls.edit')"
:aria-label="$t('campaigns.map.walls.edit')" :aria-pressed="editingWalls.toString()" @click="toggleWallEditing">
<img class="tool-icon" src="/icons/iconoir/regular/border-out.svg" alt="" aria-hidden="true">
</button>
<button class="viewer-tool" type="button" :title="$t('campaigns.map.zoom-out')" :aria-label="$t('campaigns.map.zoom-out')" @click="zoomFromToolbar(false)">
<img class="tool-icon" src="/icons/iconoir/regular/minus.svg" alt="" aria-hidden="true">
</button>
<span class="zoom-readout">{{ zoomPercent }}</span>
<button class="viewer-tool" type="button" :title="$t('campaigns.map.zoom-in')" :aria-label="$t('campaigns.map.zoom-in')" @click="zoomFromToolbar(true)">
<img class="tool-icon" src="/icons/iconoir/regular/plus.svg" alt="" aria-hidden="true">
</button>
<button class="viewer-tool" type="button" :title="$t('campaigns.map.fit')" :aria-label="$t('campaigns.map.fit')" @click="fitToWindow">
<img class="tool-icon" src="/icons/iconoir/regular/expand.svg" alt="" aria-hidden="true">
</button>
<button class="viewer-tool" type="button" :title="$t('campaigns.map.edit')" :aria-label="$t('campaigns.map.edit')" @click="editMap">
<img class="tool-icon" src="/icons/iconoir/regular/edit.svg" alt="" aria-hidden="true">
</button>
<button v-if="anchored" class="viewer-tool" type="button" :title="$t('campaigns.map.open-window')" :aria-label="$t('campaigns.map.open-window')"
@click="emit('detach')">
<img class="tool-icon" src="/icons/iconoir/regular/open-in-window.svg" alt="" aria-hidden="true">
</button>
</div>
</div>
<div
ref="viewport"
class="map-viewport"
:class="{ dragging }"
@wheel.prevent="onWheel"
@pointerdown="onPointerDown"
@pointermove="onPointerMove"
@pointerup="onPointerUp"
@pointercancel="onPointerUp"
@contextmenu.prevent="onMapContextMenu"
@dragover="onMapDragOver"
@dragleave="onMapDragLeave"
@drop.prevent="onMapDrop"
>
<template v-if="imageUrl">
<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>
<!-- Walls are drawn in screen space like the pins, so their lines stay thin at any
zoom. They only catch the mouse while the editor is open, and never when there
is no image to hold them. -->
<svg v-if="imageUrl && (walls.length || drawingWall || editingWalls)" class="map-walls" :class="{ editing: editingWalls }">
<g v-for="wall in walls" :key="wall._id">
<line class="wall-line" :class="wallClasses(wall)" v-bind="wallScreen(wall)"></line>
<template v-if="editingWalls">
<line
class="wall-hit"
role="button"
tabindex="0"
:aria-label="$t('campaigns.map.walls.wall')"
v-bind="wallScreen(wall)"
@pointerdown="onWallPointerDown($event, wall)"
@pointermove="onWallPointerMove"
@pointerup="onWallPointerUp"
@pointercancel="onWallPointerUp"
@contextmenu.stop.prevent="onWallContextMenu(wall)"
@keydown="onWallKeydown($event, wall)"
></line>
<circle
v-for="end in [0, 1]"
:key="end"
class="wall-end"
:cx="end === 0 ? wallScreen(wall).x1 : wallScreen(wall).x2"
:cy="end === 0 ? wallScreen(wall).y1 : wallScreen(wall).y2"
r="5"
@pointerdown="onWallEndPointerDown($event, wall, end)"
@pointermove="onWallEndPointerMove"
@pointerup="onWallEndPointerUp"
@pointercancel="onWallEndPointerUp"
></circle>
</template>
</g>
<line v-if="drawingWall" class="wall-draft" v-bind="ToScreenWall(drawingWall, viewState())"></line>
</svg>
<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>
<div class="map-tokens">
<button
v-for="token in tokens"
:key="token._id"
class="map-token"
:class="{ moving: movingToken && String(movingToken.token?._id) === String(token._id) }"
type="button"
:style="tokenStyle(token)"
:title="tokenLabel(token) || $t('campaigns.map.tokens.token')"
:aria-label="tokenLabel(token) || $t('campaigns.map.tokens.token')"
draggable="false"
@pointerdown="onTokenPointerDown($event, token)"
@pointermove="onTokenPointerMove"
@pointerup="onTokenPointerUp"
@pointercancel="onTokenPointerUp"
@dblclick="openTokenSheet(token)"
@contextmenu.stop.prevent="onTokenContextMenu(token)"
@keydown="onTokenKeydown($event, token)"
>
<span class="token-initials" aria-hidden="true">{{ tokenInitials(token) }}</span>
<img v-if="tokenImage(token)" class="token-image" :src="tokenImage(token)" alt="" draggable="false" @error="onTokenImageError(token)">
<span class="token-label">{{ tokenLabel(token) }}</span>
</button>
</div>
<div v-if="draggingActor" class="map-drop-hint">{{ $t('campaigns.map.tokens.drop-hint') }}</div>
<div v-if="editingWalls" class="map-walls-hint">{{ $t('campaigns.map.walls.hint') }}</div>
</template>
<div v-else class="map-empty">
{{ $t('campaigns.map.no-image') }}
<button class="map-edit" type="button" @click="editMap">{{ $t('campaigns.map.upload-photo') }}</button>
</div>
</div>
</div>
</template>
<style scoped>
.map-pane { width: 100%; flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.viewer-bar { width: 100%; box-sizing: border-box; display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 10px; border-bottom: 1px solid var(--color-border); background: var(--color-background-light); }
.viewer-identity { min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.viewer-identity strong { font-family: MrEavesRemake; overflow-wrap: anywhere; }
.viewer-meta { font-size: 11px; opacity: .72; }
.viewer-tools { display: flex; align-items: center; gap: 4px; }
.viewer-tool { width: 30px; height: 30px; margin: 0; padding: 0; border: 1px solid var(--color-border); border-radius: 7px; background: var(--color-background-soft); display: flex; align-items: center; justify-content: center; cursor: pointer; }
.viewer-tool:hover { background: var(--color-button-hover); }
.viewer-tool.selected { border-color: var(--color-link); background: var(--color-button-hover); }
.tool-icon { width: 16px; height: 16px; filter: invert(var(--color-icon-invert)); }
.zoom-readout { min-width: 46px; text-align: center; font-size: 12px; }
.map-viewport { position: relative; width: 100%; flex: 1; min-height: 0; overflow: hidden; background-color: var(--color-background); cursor: grab; touch-action: none; }
.map-viewport.dragging { cursor: grabbing; }
.map-image { position: absolute; top: 0; left: 0; max-width: none; transform-origin: top left; user-select: none; }
.map-grid { position: absolute; top: 0; left: 0; opacity: .55; pointer-events: none; }
/* Pins live in image pixels but are drawn in screen space (see ToScreenPoint), so the overlay stays
unscaled and their markers are readable at every zoom. Only the markers catch the mouse. */
.map-pins { position: absolute; inset: 0; pointer-events: none; }
.map-pin {
position: absolute; transform: translate(-50%, -100%); pointer-events: auto;
display: flex; align-items: center; gap: 4px; margin: 0; padding: 3px 6px;
border: 1px solid var(--color-link); border-radius: 7px;
background: var(--color-background-soft); color: var(--color-text);
font-size: 11px; cursor: pointer; box-shadow: 0px 0px 6px -1px rgba(0,0,0,0.55);
}
.map-pin:hover { background: var(--color-button-hover); }
.map-pin:focus-visible { outline: 1px solid var(--color-link); }
.pin-icon { width: 12px; height: 12px; filter: invert(var(--color-icon-invert)); }
/* The note's name only when it is asked for: a map full of labels is a map nobody can read. */
.pin-label { display: none; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.map-pin:hover .pin-label, .map-pin:focus-visible .pin-label { display: inline; }
/* 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);
}
/* Walls are drawn in screen space like the pins, so their lines stay thin at any zoom. A sight
wall is red, a wall that only stops movement grey, a door green — close to how Foundry paints
them on its own scenes. Only the editor's hit lines and handles catch the mouse. */
.map-walls { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; overflow: visible; }
.wall-line { stroke: var(--color-red); stroke-width: 2; opacity: .85; pointer-events: none; }
.wall-line.wall-move-only { stroke: var(--color-gray); }
.wall-line.wall-door { stroke: var(--color-green); stroke-width: 3; }
.wall-line.selected { stroke: var(--color-link); opacity: 1; }
/* The grabbable line and the endpoint handles: each wall gives its own hit area, wide enough that
the pointer finds it at any zoom. */
.wall-hit { stroke: transparent; stroke-width: 16; stroke-linecap: round; pointer-events: stroke; cursor: move; }
.wall-hit:focus-visible { stroke: var(--color-link); stroke-opacity: .35; outline: none; }
.wall-end { fill: var(--color-background-soft); stroke: var(--color-link); stroke-width: 1.5; pointer-events: auto; cursor: crosshair; }
.wall-draft { stroke: var(--color-link); stroke-width: 2; stroke-dasharray: 6 4; pointer-events: none; }
/* Shown while the wall editor is open, so the gestures it answers to are at hand. */
.map-walls-hint {
position: absolute; bottom: 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); }
</style>