Files
maptool/public/js/preview.js
T

98 lines
3.1 KiB
JavaScript

import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
// Hovering a list item with a place (mouse), or pressing and holding it
// (touch), shows that place on the map for a moment; leaving or letting go
// puts the map back where it was. A click or tap commits: the item's own
// click handler moves the map for good, and nothing is restored.
const HOLD_MS = 400;
const RESTORE_DELAY_MS = 150; // moving straight to the next item doesn't bounce back in between
const DURATION_MS = 300;
let saved = null; // the camera before the first preview
let restoreTimer = null;
let marker = null;
const wiredMaps = new WeakSet();
// target() → { lngLat: [lon, lat] } or { bbox: [w, s, e, n] }.
export function wirePreview(map, element, target) {
// Panning the map yourself during a preview keeps where you are now.
if (!wiredMaps.has(map)) {
wiredMaps.add(map);
map.on("dragstart", commit);
}
let holdTimer = null;
let held = false;
element.addEventListener("pointerenter", (event) => {
if (event.pointerType === "mouse") show(map, target());
});
element.addEventListener("pointerleave", (event) => {
if (event.pointerType === "mouse") restoreSoon(map);
});
element.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse") return;
held = false;
holdTimer = setTimeout(() => {
held = true;
show(map, target());
}, HOLD_MS);
});
const release = () => {
clearTimeout(holdTimer);
if (held) restoreSoon(map);
};
element.addEventListener("pointerup", release);
element.addEventListener("pointercancel", release); // the list scrolled instead
element.addEventListener("contextmenu", (event) => event.preventDefault()); // the long press is ours
// Capture, so this runs before the item's own click handler.
element.addEventListener(
"click",
(event) => {
if (held) {
// The end of a hold, not a tap.
held = false;
event.preventDefault();
event.stopImmediatePropagation();
return;
}
commit();
},
true,
);
}
function show(map, { lngLat, bbox }) {
clearTimeout(restoreTimer);
saved ||= { center: map.getCenter(), zoom: map.getZoom(), bearing: map.getBearing(), pitch: map.getPitch() };
const point = bbox && (bbox[0] !== bbox[2] || bbox[1] !== bbox[3]) ? null : lngLat || bbox.slice(0, 2);
if (point) {
map.easeTo({ center: point, zoom: Math.max(saved.zoom, 14), duration: DURATION_MS });
if (!marker) {
const element = document.createElement("div");
element.className = "search-highlight preview-highlight";
marker = new Marker({ element });
}
marker.setLngLat(point).addTo(map);
} else {
map.fitBounds(bbox, { padding: 40, maxZoom: 15, duration: DURATION_MS });
marker?.remove();
}
}
function restoreSoon(map) {
clearTimeout(restoreTimer);
restoreTimer = setTimeout(() => {
if (saved) map.easeTo({ ...saved, duration: DURATION_MS });
saved = null;
marker?.remove();
}, RESTORE_DELAY_MS);
}
function commit() {
clearTimeout(restoreTimer);
saved = null;
marker?.remove();
}