Files
dragonroll/frontend/app/components/viewer/map/MapViewerPane.vue
Gitea OpenCode Agent 8510a93027
All checks were successful
Test / test (push) Successful in 2s
Fix issue #101: Add lights to maps
2026-10-16 01:59:57 +00:00

1110 lines
48 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 { CastLight, SnapToGridVertex, WallAt } from '~/services/MapLighting';
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);
// Lighting over the map: the dark the lights are carved out of. Off by default, so a map reads as the
// picture it is until whoever is running the table asks for the dark.
const showLighting = ref(false);
// Drawing walls instead of panning the map: a wall is dragged from one corner of the grid to another.
const wallMode = ref(false);
// The wall being drawn — the corner it starts at and the one the pointer has reached. It is written
// once, when the pointer lets go, so drawing a wall is not one request per mouse move.
const drawingWall = ref(null);
let wallPointerId = null;
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;
// The wall tool takes the pointer for itself: holding the map then draws a wall instead of moving it.
if (wallMode.value && startWallDrag(event)) return;
dragging.value = true;
pointerId = event.pointerId;
lastPointer = { x: event.clientX, y: event.clientY };
viewport.value.setPointerCapture?.(event.pointerId);
}
function onPointerMove(event) {
if (moveWallDrag(event)) 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 (await endWallDrag(event)) return;
if (event.pointerId !== pointerId) 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;
const items = [];
if (!noteOptions.value.length) items.push({ name: t('campaigns.map.pins.none'), action: () => HideContextMenu() });
else {
items.push({
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); }
}))
});
}
items.push({ divider: true });
items.push({
name: t('campaigns.map.lights.add'),
icon: '/icons/iconoir/regular/fire-flame.svg',
action: () => { HideContextMenu(); placeLight(spot); }
});
// A wall is a line, not a marker to hold: right clicking along it is how it is taken off again.
const wall = WallAt(spot, walls.value, WALL_PICK_PX / Math.max(0.05, zoom.value));
if (wall) {
items.push({
name: t('campaigns.map.walls.remove'),
icon: '/icons/iconoir/regular/xmark-circle.svg',
action: () => { HideContextMenu(); removeWall(wall); }
});
}
ShowContextMenu(items);
}
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))];
}
// --- Lights, and the walls that stop them ---
// A light shines from one spot of the image and is as free to place as a pin. The walls of the map are
// what cuts its reach into a shadow: CastLight works out the shape a light paints and the canvas below
// paints that shape out of the dark laid over the map.
// A new light covers this much of the map it is placed on, and half of that is bright light.
const LIGHT_CELLS = 3;
// How near a line a right click has to come to mean that wall, in screen pixels (it is divided by the
// zoom to become image pixels, so picking a wall is as easy zoomed out as zoomed in).
const WALL_PICK_PX = 10;
const lightingCanvas = ref(null);
const lights = computed(() => map.value?.lights ?? []);
const walls = computed(() => map.value?.walls ?? []);
// The light a pointer is holding, and the spot it holds it at: like a token, the move stays local until
// the pointer lets go, so dragging a light across the map is one save and not one per mouse move.
const movingLight = ref(null);
let lightPointerId = null;
// A colour from the theme the canvas paints with. The canvas cannot be styled with `var(--color-…)`
// like a stylesheet, so it asks the document for the same variable the stylesheets use.
function themeColor(name, fallback) {
if (typeof window === 'undefined' || typeof getComputedStyle !== 'function') return fallback;
return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
}
// A hex colour with an alpha end ('#ffc46b' + '4d'), because a canvas gradient needs its stops spelled
// out. Anything that is not a plain hex colour is painted as it is.
function withAlpha(color, alpha) {
const value = String(color ?? '').trim();
if (/^#[0-9a-f]{6}$/i.test(value)) return `${value}${alpha}`;
if (/^#[0-9a-f]{3}$/i.test(value)) return `#${value.slice(1)}${value.slice(1)}${alpha}`;
return value;
}
// The light a marker is drawn for: the spot it is being held at while a pointer drags it, and its own
// spot otherwise.
function heldLight(light) {
if (movingLight.value && String(movingLight.value.light?._id) === String(light?._id)) return movingLight.value;
return { x: Number(light?.x) || 0, y: Number(light?.y) || 0 };
}
function lightStyle(light) {
const point = ToScreenPoint(heldLight(light), viewState());
return { left: `${point.x}px`, top: `${point.y}px` };
}
// The reach a light is given when it is placed: enough of the map to matter at the grid it stands on.
function defaultLightReach() {
const cell = Math.max(1, Number(map.value?.gridSize) || 50);
const radius = Math.round(cell * LIGHT_CELLS);
return { radius, bright: Math.round(radius / 2) };
}
async function placeLight(spot) {
const reach = defaultLightReach();
await updateMap('/map/place-light', {
id: map.value?._id, x: spot.x, y: spot.y, ...reach
}, t('campaigns.map.lights.error'));
}
async function removeLight(light) {
await updateMap('/map/remove-light', { id: map.value?._id, light: light?._id }, t('campaigns.map.lights.error'));
}
function onLightPointerDown(event, light) {
// Holding a light moves the light, never the map.
event.stopPropagation();
if (event.button !== 0) return;
lightPointerId = event.pointerId;
event.currentTarget.setPointerCapture?.(event.pointerId);
movingLight.value = { light: { ...light }, x: Number(light.x) || 0, y: Number(light.y) || 0 };
}
function onLightPointerMove(event) {
if (!movingLight.value || event.pointerId !== lightPointerId) return;
const spot = imagePointOf(event);
// Dragged off the image, the light keeps its spot: a light is never lost over the edge.
if (!spot) return;
movingLight.value = { ...movingLight.value, x: spot.x, y: spot.y };
}
async function onLightPointerUp(event) {
if (!movingLight.value || event.pointerId !== lightPointerId) return;
const { light, x, y } = movingLight.value;
lightPointerId = null;
movingLight.value = null;
event.currentTarget?.releasePointerCapture?.(event.pointerId);
if (x === Number(light.x) && y === Number(light.y)) return;
await updateMap('/map/update-light', { id: map.value?._id, light: light._id, x, y }, t('campaigns.map.lights.error'));
}
function onLightContextMenu(light) {
ShowContextMenu([{
name: t('campaigns.map.lights.remove'),
icon: '/icons/iconoir/regular/xmark-circle.svg',
action: () => { HideContextMenu(); removeLight(light); }
}]);
}
// Delete takes a focused light off the map, like it does a focused token.
async function onLightKeydown(event, light) {
if (event.key === 'Delete' || event.key === 'Backspace') {
event.preventDefault();
await removeLight(light);
}
}
// --- Drawing walls ---
// With the wall tool on, the pointer draws instead of panning: it is held down at one corner of the
// grid and let go at another, and the wall between those two corners is what gets saved.
// Holds down the first corner of a wall, or says the wall tool has nothing to hold (off the image).
function startWallDrag(event) {
const spot = imagePointOf(event);
if (!spot) return false;
const corner = SnapToGridVertex(spot, grid.value);
if (!corner) return false;
wallPointerId = event.pointerId;
viewport.value?.setPointerCapture?.(event.pointerId);
drawingWall.value = { x1: corner.x, y1: corner.y, x2: corner.x, y2: corner.y };
return true;
}
function moveWallDrag(event) {
if (!drawingWall.value || event.pointerId !== wallPointerId) return false;
const spot = imagePointOf(event);
// Off the image the wall keeps the end it had: a wall cannot hang outside of the map.
if (!spot) return true;
const corner = SnapToGridVertex(spot, grid.value);
if (!corner) return true;
if (corner.x === drawingWall.value.x2 && corner.y === drawingWall.value.y2) return true;
drawingWall.value = { ...drawingWall.value, x2: corner.x, y2: corner.y };
return true;
}
async function endWallDrag(event) {
if (!drawingWall.value || event.pointerId !== wallPointerId) return false;
const wall = drawingWall.value;
wallPointerId = null;
drawingWall.value = null;
viewport.value?.releasePointerCapture?.(event.pointerId);
// Dragged out and back to the same corner is not a wall: it stops nothing and cannot be picked
// up again, so it is dropped where it was drawn.
if (wall.x1 === wall.x2 && wall.y1 === wall.y2) return true;
await saveWall(wall);
return true;
}
async function saveWall(wall) {
await updateMap('/map/wall', { id: map.value?._id, ...wall }, t('campaigns.map.walls.error'));
}
async function removeWall(wall) {
await updateMap('/map/remove-wall', { id: map.value?._id, wall: wall?._id }, t('campaigns.map.walls.error'));
}
// --- Painting the lights ---
// One canvas over the map, drawn in screen pixels like the pins and the tokens, and repainted whenever
// the view or the map changes. With the lighting on it lays the dark over the image and erases the shape
// of every light out of it, so what is left dark is exactly what its walls hide. With the lighting off
// the same shapes are drawn as thin outlines, which is what makes reaching for a light's size possible
// while it is still being placed.
function imageScreenRect() {
const origin = ToScreenPoint({ x: 0, y: 0 }, viewState());
return {
x: origin.x,
y: origin.y,
width: imageSize.value.width * zoom.value,
height: imageSize.value.height * zoom.value
};
}
function tracePolygon(context, points, view) {
context.beginPath();
points.forEach((point, index) => {
const screen = ToScreenPoint(point, view);
if (index) context.lineTo(screen.x, screen.y);
else context.moveTo(screen.x, screen.y);
});
context.closePath();
}
function paintDarkness(context, image) {
const view = viewState();
context.save();
context.fillStyle = themeColor('--color-map-darkness', '#000000d9');
context.fillRect(image.x, image.y, image.width, image.height);
// The lights erase the dark they stand in: only how much a gradient is transparent matters here, so
// a light fades from fully lit at its middle to nothing at the end of its reach.
context.globalCompositeOperation = 'destination-out';
for (const light of lights.value) {
const shape = CastLight(light, walls.value);
if (!shape.length) continue;
const centre = ToScreenPoint(heldLight(light), view);
const reach = Math.max(1, (Number(light.radius) || 0) * zoom.value);
const core = Math.max(0, Math.min(1, (Number(light.bright) || 0) / (Number(light.radius) || 1)));
context.save();
tracePolygon(context, shape, view);
context.clip();
const gradient = context.createRadialGradient(centre.x, centre.y, 0, centre.x, centre.y, reach);
gradient.addColorStop(0, '#000000ff');
gradient.addColorStop(core, '#000000f5');
gradient.addColorStop(1, '#00000000');
context.fillStyle = gradient;
context.fillRect(image.x, image.y, image.width, image.height);
context.restore();
}
// The tint of a coloured light, laid back over the light it colours: a lantern reads warm and a
// spell cold, and a light with no colour of its own leaves the map as it is.
context.globalCompositeOperation = 'source-over';
for (const light of lights.value) {
if (!light.color) continue;
const shape = CastLight(light, walls.value);
if (!shape.length) continue;
const centre = ToScreenPoint(heldLight(light), view);
const reach = Math.max(1, (Number(light.radius) || 0) * zoom.value);
context.save();
tracePolygon(context, shape, view);
context.clip();
const gradient = context.createRadialGradient(centre.x, centre.y, 0, centre.x, centre.y, reach);
gradient.addColorStop(0, withAlpha(light.color, '33'));
gradient.addColorStop(1, withAlpha(light.color, '00'));
context.fillStyle = gradient;
context.fillRect(image.x, image.y, image.width, image.height);
context.restore();
}
context.restore();
}
function paintLightOutlines(context) {
const view = viewState();
context.save();
context.lineWidth = 1;
for (const light of lights.value) {
const shape = CastLight(light, walls.value);
if (!shape.length) continue;
tracePolygon(context, shape, view);
context.strokeStyle = withAlpha(light.color || '#ffffff', '59');
context.stroke();
}
context.restore();
}
function paintWalls(context) {
if (!walls.value.length && !drawingWall.value) return;
const view = viewState();
context.save();
context.lineCap = 'round';
context.strokeStyle = themeColor('--color-map-wall', '#e06c75');
// The wall tool asks for a firmer line: it is the tool that has to see what it has drawn already.
context.lineWidth = wallMode.value ? 3 : 2;
for (const wall of walls.value) {
const from = ToScreenPoint({ x: Number(wall.x1) || 0, y: Number(wall.y1) || 0 }, view);
const to = ToScreenPoint({ x: Number(wall.x2) || 0, y: Number(wall.y2) || 0 }, view);
context.beginPath();
context.moveTo(from.x, from.y);
context.lineTo(to.x, to.y);
context.stroke();
}
// The wall being drawn, along the grid corners the pointer has reached so far.
if (drawingWall.value) {
context.setLineDash([6, 4]);
const from = ToScreenPoint({ x: drawingWall.value.x1, y: drawingWall.value.y1 }, view);
const to = ToScreenPoint({ x: drawingWall.value.x2, y: drawingWall.value.y2 }, view);
context.beginPath();
context.moveTo(from.x, from.y);
context.lineTo(to.x, to.y);
context.stroke();
}
context.restore();
}
function drawLighting() {
const canvas = lightingCanvas.value;
const bounds = viewport.value?.getBoundingClientRect();
if (!canvas || !bounds) return;
const width = Math.max(1, Math.round(bounds.width));
const height = Math.max(1, Math.round(bounds.height));
if (canvas.width !== width) canvas.width = width;
if (canvas.height !== height) canvas.height = height;
const context = canvas.getContext?.('2d');
if (!context) return;
context.clearRect(0, 0, width, height);
if (!imageUrl.value) return;
if (showLighting.value) paintDarkness(context, imageScreenRect());
else paintLightOutlines(context);
paintWalls(context);
}
// Every move of the view, and every light or wall that changes, is painted again.
watch(
[zoom, pan, imageSize, showLighting, wallMode, drawingWall, lights, walls, imageUrl],
() => nextTick(drawLighting),
{ deep: true }
);
onMounted(() => {
window.addEventListener('resize', drawLighting);
nextTick(drawLighting);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', drawLighting);
});
// 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;
movingLight.value = null;
drawingWall.value = null;
wallPointerId = 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);
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);
});
</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: showLighting }" type="button" :title="$t('campaigns.map.toggle-lighting')"
:aria-label="$t('campaigns.map.toggle-lighting')" :aria-pressed="showLighting.toString()" @click="showLighting = !showLighting">
<img class="tool-icon" src="/icons/iconoir/regular/light-bulb-on.svg" alt="" aria-hidden="true">
</button>
<button class="viewer-tool" :class="{ selected: wallMode }" type="button" :title="$t('campaigns.map.toggle-walls')"
:aria-label="$t('campaigns.map.toggle-walls')" :aria-pressed="wallMode.toString()" @click="wallMode = !wallMode">
<img class="tool-icon" src="/icons/iconoir/regular/linear.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, 'wall-mode': wallMode }"
@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>
<canvas ref="lightingCanvas" class="map-lighting" aria-hidden="true"></canvas>
<div class="map-lights">
<button
v-for="light in lights"
:key="light._id"
class="map-light"
:class="{ moving: movingLight && String(movingLight.light?._id) === String(light._id) }"
type="button"
:style="lightStyle(light)"
:title="$t('campaigns.map.lights.light')"
:aria-label="$t('campaigns.map.lights.light')"
draggable="false"
@pointerdown="onLightPointerDown($event, light)"
@pointermove="onLightPointerMove"
@pointerup="onLightPointerUp"
@pointercancel="onLightPointerUp"
@contextmenu.stop.prevent="onLightContextMenu(light)"
@keydown="onLightKeydown($event, light)"
>
<img class="light-icon" src="/icons/iconoir/regular/fire-flame.svg" alt="" aria-hidden="true">
</button>
</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>
<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="wallMode" class="map-drop-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; }
.map-viewport.wall-mode { cursor: crosshair; }
/* The lights are painted on a canvas over the image and in screen space, like the pins: the dark over
the map and the shape each light cuts in it are redrawn whenever the view moves (see drawLighting).
The canvas never catches the mouse; the light markers below do that. */
.map-lighting { position: absolute; top: 0; left: 0; pointer-events: none; }
.map-lights { position: absolute; inset: 0; pointer-events: none; }
.map-light {
position: absolute; transform: translate(-50%, -50%); pointer-events: auto;
display: flex; align-items: center; justify-content: center; width: 26px; height: 26px;
margin: 0; padding: 0; border: 1px 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-light:hover { background: var(--color-button-hover); }
.map-light:focus-visible { outline: 1px solid var(--color-link); outline-offset: 2px; }
.map-light.moving { cursor: grabbing; }
.light-icon { width: 14px; height: 14px; filter: invert(var(--color-icon-invert)); }
/* 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);
}
.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>