import { Map as MaplibreMap, NavigationControl, Popup, ScaleControl, addProtocol, } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { GpxPanelControl } from "/js/gpx.js"; import { OverlaysControl } from "/js/overlays.js"; import { GnssControl } from "/js/gnss.js"; import { LiveTrackPanelControl } from "/js/livetrack.js"; import { TrackProfilePanel } from "/js/track_profile.js"; import { MeasureControl } from "/js/measure.js"; import { NotesControl } from "/js/notes.js"; import { PluginsControl } from "/js/plugins.js"; import { LocateControl } from "/js/locate.js"; import { SearchControl } from "/js/search.js"; import { OfflineDataControl } from "/js/offline_data.js"; import { RoutePanelControl } from "/js/route.js"; import { WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON, LOCK_ICON, UNLOCK_ICON } from "/js/icons.js"; import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js"; import { getPosition } from "/vendor/suncalc/suncalc.js"; import { addRoutePoint, setupSidePanelModes } from "/js/panels.js"; import { isLoggedIn } from "/js/auth.js"; import { DebugControl } from "/js/debug.js"; import { setupUpdate } from "/js/update.js"; import { patchOnlineStyle, patternImage, PATTERN_IDS, NightMap } from "/js/map_themes.js"; import { offerSharedFiles } from "/js/share_import.js"; import HomeButton from "/vendor/npmap-home-button/home-button.esm.js"; import OverviewMap from "/vendor/npmap-overview/overview.esm.js"; import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { setupDriving } from "/js/driving.js"; import { elevationAt } from "/js/dem.js"; const CENTER = [17.1077, 48.1486]; const ZOOM = 13; const ONLINE_STYLE_URL = "https://tiles.openfreemap.org/styles/liberty"; // Fetched (not just referenced by URL) so its colors can be patched before // the map ever sees it — MapLibre accepts a style object anywhere it'd // accept a style URL, so every use of onlineStyle() (applyStyle's // map.setStyle) needs no change. This runs before the map — and the rest // of the page's setup — is constructed (see the top-level await below), so // it falls back to the plain URL, letting MapLibre fetch and render it // unpatched, both when the fetch fails outright and when it's just slow // (a 3s timeout): this app is meant to work offline in the field, and // blocking the entire page on a remote style server would undermine that // even though this particular fetch is only for the online map. // Kept unpatched; onlineStyle() patches a fresh copy for each setStyle. async function loadOnlineStyle() { try { const response = await fetch(ONLINE_STYLE_URL, { signal: AbortSignal.timeout(3000) }); return await response.json(); } catch (err) { return ONLINE_STYLE_URL; } } const ONLINE_STYLE_TEMPLATE = await loadOnlineStyle(); function onlineStyle() { if (typeof ONLINE_STYLE_TEMPLATE === "string") return ONLINE_STYLE_TEMPLATE; return patchOnlineStyle(structuredClone(ONLINE_STYLE_TEMPLATE)); } // A vendored copy of the same Liberty style ONLINE_STYLE_TEMPLATE fetches live // (public/vendor/liberty-style/liberty.json — a point-in-time snapshot, not // auto-updated) that offlineStyle() below patches+repoints the exact same // way. Offline mode can't depend on ONLINE_STYLE_URL actually being // reachable — that fetch failing/timing out is the normal case in the // field, not an edge case — so this is a local, same-origin fetch instead // (fast and always available, since it's served by this app itself). const OFFLINE_STYLE_TEMPLATE = await fetch("/vendor/liberty-style/liberty.json").then((response) => response.json()); const protocol = new pmtiles.Protocol(); addProtocol("pmtiles", protocol.tile); // Builds the offline style from OFFLINE_STYLE_TEMPLATE — the identical // Liberty JSON + patchOnlineStyle recolor (map_themes.js) as the online map, just // repointed at a local PMTiles source instead of tiles.openfreemap.org. // This works because data/offline.pmtiles is now built by Planetiler's own // OpenMapTiles profile (see docs/development.adoc), the same vector schema // Liberty expects — before that, offline tiles used a different schema // (protomaps' own basemaps) needing a completely separate hand-tuned // theme (protomaps-themes-base + OFFLINE_THEME) that could never be made // to match the online look exactly, no matter how much either // side got tuned. // // glyphs/sprite point at vendored local copies (public/vendor/fonts, // public/vendor/liberty-sprite) rather than tiles.openfreemap.org's — // glyphs are Latin-only (see docs/architecture.adoc: labels in other // scripts won't render offline), sprite is a one-time snapshot like // OFFLINE_STYLE_TEMPLATE itself. ne2_shaded (Liberty's low-zoom shaded- // relief backdrop, z0-6 only) is left pointing at its remote URL // unchanged — offline usage is regional, not whole-earth zoomed out, so // this only ever silently fails to load at a zoom level offline users // aren't in, the same graceful-degradation story as this app's other // online-only extras (Wikipedia, live radar). function offlineStyle() { const style = patchOnlineStyle(structuredClone(OFFLINE_STYLE_TEMPLATE)); style.sources.openmaptiles.url = `pmtiles://${window.location.origin}/tiles/offline.pmtiles`; style.glyphs = `${window.location.origin}/vendor/fonts/{fontstack}/{range}.pbf`; style.sprite = `${window.location.origin}/vendor/liberty-sprite/ofm`; return style; } // The Online/Offline choice: the first group of the On the map panel // (the Overlays one, overlays.js), no rail item or panel of its own. class LayerToggleControl { constructor(onSelect) { this._onSelect = onSelect; this._panel = document.querySelector(".onthemap-map"); } mount() { this._panel.querySelectorAll(".basemap-panel__option").forEach((button) => { button.addEventListener("click", () => this._onSelect(button.dataset.style)); }); } setActive(name) { this._panel.querySelectorAll(".basemap-panel__option").forEach((button) => { button.classList.toggle("active", button.dataset.style === name); }); } // Called once it's known there's no offline map to switch to (see the // /api/offline-tiles check below) — an Online/Offline switch doesn't make // sense to show at all when Offline was never going to work. The legend // link stays. hideSources() { this._panel.querySelector(".basemap-panel__sources").hidden = true; } } // Tilts the camera between a flat top-down view and a fixed 3D-perspective // pitch — bearing stays untouched, so this is purely "look at it from an // angle", not a rotate/compass control. Tilted, the ground is raised into // real 3D relief (OverlaysControl.syncTerrain, overlays.js), with or // without the "Terrain shading" overlay. const PITCH_3D = 60; class PitchToggleControl { onAdd(map) { this._map = map; this._container = document.createElement("div"); this._container.className = "maplibregl-ctrl maplibregl-ctrl-group pitch-toggle-ctrl"; this._button = document.createElement("button"); this._button.type = "button"; this._button.className = "pitch-toggle-ctrl__button"; this._button.addEventListener("click", () => this._toggle()); this._container.appendChild(this._button); this._update = () => this._render(); map.on("pitchend", this._update); this._render(); return this._container; } onRemove() { this._map.off("pitchend", this._update); this._container.remove(); } getDefaultPosition() { return "top-left"; } // Set once overlaysControl exists (it's built later in this file) — // lets raised terrain (OverlaysControl.syncTerrain, see overlays.js) // follow the pitch toggle without this control needing to know anything // about hillshade/DEM sources itself. setOverlaysControl(overlaysControl) { this._overlaysControl = overlaysControl; this._overlaysControl.syncTerrain(this._map.getPitch() > 0); } _toggle() { this._map.easeTo({ pitch: this._map.getPitch() > 0 ? 0 : PITCH_3D, duration: 300 }); } _render() { const is3d = this._map.getPitch() > 0; this._button.textContent = is3d ? "2D" : "3D"; this._button.title = is3d ? "Switch to 2D view" : "Switch to 3D view"; this._button.setAttribute("aria-label", this._button.title); this._button.classList.toggle("active", is3d); this._overlaysControl?.syncTerrain(is3d); } } // Locks the map north-up (on by default): a two-finger gesture on a // tablet rotates it far too easily. Unlocked, it rotates like any map and // NavigationControl's compass turns it back north. class RotationLockControl { onAdd(map) { this._map = map; this._container = document.createElement("div"); this._container.className = "maplibregl-ctrl maplibregl-ctrl-group rotation-lock-ctrl"; this._button = document.createElement("button"); this._button.type = "button"; this._button.addEventListener("click", () => this._set(!this._locked)); this._container.appendChild(this._button); let stored = null; try { stored = localStorage.getItem("rotationLocked"); } catch {} this._set(stored !== "false"); return this._container; } onRemove() { this._container.remove(); } _set(locked) { this._locked = locked; const action = locked ? "disableRotation" : "enableRotation"; this._map.touchZoomRotate[action](); this._map.keyboard[action](); this._map.dragRotate[locked ? "disable" : "enable"](); if (locked && this._map.getBearing() !== 0) this._map.easeTo({ bearing: 0, duration: 300 }); this._button.innerHTML = locked ? LOCK_ICON : UNLOCK_ICON; this._button.title = locked ? "Rotation locked (north up), click to allow rotating" : "Rotation allowed, click to lock north up"; this._button.setAttribute("aria-label", this._button.title); this._button.classList.toggle("active", locked); try { localStorage.setItem("rotationLocked", String(locked)); } catch {} } } const initialStyle = onlineStyle(); const map = new MaplibreMap({ container: "map", style: initialStyle, center: CENTER, zoom: ZOOM, // MapLibre's built-in Hash control: keeps #map=zoom/lat/lon in the URL in // sync with the view (via history.replaceState, so panning doesn't spam // the back button) and, if the page loads with one already in the URL, // opens there instead of the default CENTER/ZOOM — the same "grab the URL // to share this exact spot" permalink pattern OSM/Google Maps use. hash: "map", }); // Home's bounds (rather than homePosition/zoom) so Home resets to an overview of // the whole country, not back to CENTER/ZOOM's initial Bratislava view — // now that the URL hash can restore any view on load (see the Hash option // above), "current view" and "the default view" are no longer the same // thing, and a home button that resets to wherever you happened to load // the page wouldn't be a home button. This is *not* "go to my location" — // that's LocateControl, below. const SLOVAKIA_BOUNDS = [ [16.83, 47.73], [22.57, 49.61], ]; // The Design canvas' Desktop: search in the topbar, the map's own buttons // in one column on the right — zoom and compass, the view (north lock, 3D, // my position), the tools (measure, note, home); the zoom level, the scale // and the coordinates in the status bar under the map. const searchControl = new SearchControl(); searchControl.mount(map, document.querySelector(".topbar__search")); // The compass shows the bearing; a click turns the map back north. map.addControl(new NavigationControl({ visualizePitch: false }), "top-right"); map.addControl(new RotationLockControl(), "top-right"); const pitchToggle = new PitchToggleControl(); map.addControl(pitchToggle, "top-right"); // Constructed here (rather than down where it's mounted, alongside the // other sidebar controls) so LocateControl can hold the same instance — // its constructor only touches `map`, mount() (which needs the sidebar // element) can still happen later. const gnssControl = new GnssControl(map); // Not MapLibre's own GeolocateControl (browser Geolocation API only) — // this app has its own GNSS receiver (the car's, see app.rb's // GNSS_LATEST), and "find my location" should prefer that over a // device's separate, often less accurate location service, but only once // the "GNSS" sidebar icon actually turns it on — not just whenever a // receiver happens to have a fix. See locate.js. map.addControl(new LocateControl(gnssControl), "top-right"); map.addControl(new MeasureControl(), "top-right"); // Writing a note needs a login (POST /api/library/notes) — no point adding a // button that can only ever end in a 401 for a logged-out viewer, same // "hide the write-only affordance" story as GpxPanelControl's own // upload/new-folder buttons. let notesControl = null; // what's here's "Save a point" (below) if (isLoggedIn()) map.addControl((notesControl = new NotesControl()), "top-right"); map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "top-right"); // ...as the artboard's three cards: zoom; the view (compass, north lock, 3D, // my position); the tools (measure, note, home). Each control keeps its own // container (their popovers hang off it), the card only groups them. { const corner = map.getContainer().querySelector(".maplibregl-ctrl-top-right"); const [nav, ...rest] = corner.children; const card = (...controls) => { const div = document.createElement("div"); div.className = "maplibregl-ctrl map-card"; div.append(...controls); corner.appendChild(div); return div; }; const view = card(...rest.slice(0, 3)); view.prepend(nav.querySelector(".maplibregl-ctrl-compass")); card(...rest.slice(3)); } // The status bar: the map's center (click to copy), the point under the // mouse, the zoom level. const cursorLabel = document.querySelector(".statusbar__cursor"); let terrainOffline = false; // set once /api/terrain-tiles answers (below) let elevationTimer = null; map.on("mousemove", ({ lngLat }) => { const at = `Cursor ${formatCoords(lngLat.lat, lngLat.lng)}`; cursorLabel.textContent = at; // the ground's height there, once the mouse rests a moment clearTimeout(elevationTimer); elevationTimer = setTimeout(async () => { const metres = await elevationAt(lngLat.lng, lngLat.lat, terrainOffline).catch(() => null); if (metres != null && cursorLabel.textContent === at) cursorLabel.textContent = `${at} · ${Math.round(metres)} m`; }, 150); }); map.getCanvasContainer().addEventListener("mouseleave", () => (cursorLabel.textContent = "")); const zoomLabel = document.querySelector(".statusbar__zoom"); const updateZoom = () => (zoomLabel.textContent = `Zoom ${map.getZoom().toFixed(1)}`); updateZoom(); map.on("zoom", updateZoom); map.addControl(new ScaleControl({ unit: "metric" }), "bottom-left"); // over the map, as in the canvas' Desktop // A small inset map showing where the current view sits in context — NPS's // own overview plugin (docs/nps-resources.adoc's "overview" entry, still on // an unmerged branch upstream). It draws its own embedded MapLibre map, so // it needs the maplibregl module itself (not just the Map class) — style // '' (the default) means it clones whatever the main map's current style // is (`this._mainMap.style.serialize()`), so it stays in sync with the // Online/Offline toggle without a second style to maintain here. Built only // once the main map's own style has loaded, matching the plugin's own // example — its internal map is constructed eagerly in the constructor, // before that clone happens in onAdd. map.once("style.load", () => { const OverviewMapControl = OverviewMap(maplibregl); map.addControl(new OverviewMapControl({}), "top-right"); }); const coordsLabel = document.querySelector(".statusbar__coords"); const updateCoords = () => { const { lng, lat } = map.getCenter(); coordsLabel.innerHTML = `${formatCoords(lat, lng)}`; }; updateCoords(); map.on("move", updateCoords); // Plain decimal degrees, not the DMS text actually shown — that's what // pastes cleanly into another map/GPS app, which is the whole point of // copying a coordinate in the first place. coordsLabel.title = "Click to copy coordinates"; coordsLabel.addEventListener("click", async () => { const { lng, lat } = map.getCenter(); try { await navigator.clipboard.writeText(`${lat.toFixed(6)}, ${lng.toFixed(6)}`); } catch { return; // clipboard API unavailable (e.g. an insecure context) — nothing to fall back to } coordsLabel.textContent = "Copied!"; setTimeout(updateCoords, 1000); }); // Sunrise/sunset for the same center point the coords above already show — // on moveend (not every "move" frame, unlike updateCoords: the sun position // barely moves between two nearby spots, not worth recomputing constantly) // plus a periodic tick so the "Xh Ym to sunset" countdown keeps counting // down even while the map sits still. const sunLabel = document.querySelector(".statusbar__sun"); const sunChart = document.querySelector(".sun-chart"); const updateSun = () => { const { lng, lat } = map.getCenter(); if (!sunChart.hidden) sunChart.innerHTML = sunChartHtml(lat, lng); const info = formatSunInfo(lat, lng); sunLabel.hidden = info === null; if (!info) return; if (info.polar) { sunLabel.innerHTML = ``; return; } const countdownGroup = info.countdown ? `` : ""; sunLabel.innerHTML = `` + `` + countdownGroup; }; // Click opens the horizon-style sun & moon chart (sun.js), kept in sync by // the same moveend/minute tick as the label itself. sunLabel.addEventListener("click", (event) => { event.stopPropagation(); sunChart.hidden = !sunChart.hidden; updateSun(); }); document.addEventListener("click", (event) => { if (!sunChart.contains(event.target)) sunChart.hidden = true; }); document.addEventListener("keydown", (event) => { if (event.key === "Escape") sunChart.hidden = true; }); updateSun(); map.on("moveend", updateSun); setInterval(updateSun, 60000); // Night mode so the screen doesn't glare in the car: "auto" follows the sun // at the map center, or by hand — the topbar button cycles them, // remembered per device. // The UI's palette (style.css, after S-52: Day, Dusk, Night) and the map's // night style: automatic by the sun, or by hand — Dusk the dark UI over the // day map, "for optional use by day as well" (docs/design.adoc). const NIGHT_MODES = { auto: ["◐", "Night mode: automatic (after sunset)"], on: ["☾", "Night mode: on"], dusk: ["◑", "Dusk: the dark UI over the day map"], off: ["☀", "Night mode: off"], }; const nightButton = document.querySelector(".topbar__night"); // On the map's Theme row: the same cycle as the topbar's button const themeButton = document.querySelector(".onthemap-theme"); themeButton.addEventListener("click", () => nightButton.click()); const nightMap = new NightMap(map); // The base style's texture patterns (grass, scrub, military hatch) and the // peak triangle are drawn at runtime rather than shipped in a sprite // sheet, added with every style before its tiles ask for them: since // MapLibre 6 an image added on styleimagemissing (or from the missing-image // resolver) misses the tiles that asked for it. const addPatterns = () => { for (const id of PATTERN_IDS) { const pattern = !map.hasImage(id) && patternImage(id); if (pattern) map.addImage(id, pattern.image, pattern.options); } }; map.on("style.load", addPatterns); if (map.isStyleLoaded()) addPatterns(); // Still the fallback for one asked for before that. map.on("styleimagemissing", ({ id }) => { const pattern = !map.hasImage(id) && patternImage(id); if (pattern) map.addImage(id, pattern.image, pattern.options); }); nightMap.base(initialStyle); let nightMode = "auto"; try { nightMode = localStorage.getItem("nightMode") || "auto"; } catch {} // The sun is checked where the map looks; zoomed out to a continent or // the world the center is meaningless (night on the other side of the // globe), so below zoom 5 the last real place is kept. let sunAt = map.getCenter(); const updateNight = () => { if (map.getZoom() >= 5) sunAt = map.getCenter(); const { lng, lat } = sunAt; const dark = nightMode === "on" || (nightMode === "auto" && getPosition(new Date(), lat, lng).altitude < 0); document.documentElement.classList.toggle("night", dark); const palette = dark ? "night" : nightMode === "dusk" ? "dusk" : null; if (palette) document.documentElement.dataset.palette = palette; else delete document.documentElement.dataset.palette; nightMap.set(dark); [nightButton.textContent, nightButton.title] = NIGHT_MODES[nightMode] || NIGHT_MODES.auto; themeButton.textContent = `${{ auto: "Auto", on: "Night", dusk: "Dusk", off: "Day" }[nightMode] || "Auto"} ›`; }; nightButton.addEventListener("click", () => { const modes = Object.keys(NIGHT_MODES); nightMode = modes[(modes.indexOf(nightMode) + 1) % modes.length]; try { localStorage.setItem("nightMode", nightMode); } catch {} updateNight(); }); updateNight(); map.on("moveend", updateNight); setInterval(updateNight, 60000); const sidebar = document.getElementById("sidebar"); // The rail of the Design canvas' Desktop, labelled: On the map (the map, // overlays), the library and imports; the route; offline data; live // (GNSS, LiveTrack); Status pinned at the bottom. const layerToggle = new LayerToggleControl(applyStyle); const profilePanel = new TrackProfilePanel(map); profilePanel.mount(); layerToggle.mount(); layerToggle.setActive("online"); const overlaysControl = new OverlaysControl(map); overlaysControl.mount(sidebar); const gpxPanel = new GpxPanelControl(map, profilePanel); gpxPanel.mount(sidebar); offerSharedFiles(gpxPanel); searchControl.setLayerOpeners({ layers: (path, result) => gpxPanel.showFeature(path, result.bbox.slice(0, 2)), hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code), }); pitchToggle.setOverlaysControl(overlaysControl); // Running a plugin needs a login (POST /api/plugins/:name/run) — same // "hide the write-only affordance" story as NotesControl above. if (isLoggedIn()) new PluginsControl(map).mount(sidebar); sidebar.insertAdjacentHTML("beforeend", `
`); const routePanel = new RoutePanelControl(map, gnssControl, profilePanel); routePanel.mount(sidebar); setupDriving(map, nightButton, routePanel, gpxPanel); new OfflineDataControl().mount(sidebar); sidebar.insertAdjacentHTML("beforeend", ``); gnssControl.mount(sidebar); new LiveTrackPanelControl(map).mount(sidebar); if (isLoggedIn()) new DebugControl().mount(sidebar); if (isLoggedIn()) setupUpdate(document.querySelector(".topbar__update"), document.querySelector(".debug-panel__update-check")); // A short name under each icon (CSS ::after), the title stays the tooltip. const RAIL_LABELS = { "Import plugins": "Import", "Offline data": "Offline", LiveTrack: "Live", "Status / debug": "Status" }; sidebar.querySelectorAll(".sidebar-icon").forEach((icon) => (icon.dataset.label = RAIL_LABELS[icon.title] ?? icon.title)); setupSidePanelModes(); function applyStyle(name) { layerToggle.setActive(name); map.setStyle(nightMap.base(name === "offline" ? offlineStyle() : onlineStyle())); } // If a local PMTiles file is present, prefer it as the default style — its // presence signals the app is meant to be used offline here. If one isn't, // the Online/Offline switch itself doesn't make sense (there's nothing to // switch to), so it's removed entirely rather than left sitting there // offering a choice that can't work. const offlineStatus = document.querySelector(".topbar__offline-status"); const ready = []; ready.push(fetch("/api/offline-tiles") .then((response) => response.json()) .then(({ available }) => { if (available) { applyStyle("offline"); } else { layerToggle.hideSources(); } offlineStatus.hidden = false; offlineStatus.classList.toggle("topbar__offline-status--ready", available); offlineStatus.title = available ? "Offline map data ready" : "No offline map data on this server"; offlineStatus.textContent = available ? "Offline ready" : "Online only"; }) .catch(() => { // Backend check failed; keep the online style and leave the switch as // is rather than guessing — this is the same-origin request itself // failing, not evidence offline tiles are actually unavailable. })); ready.push(fetch("/api/terrain-tiles") .then((response) => response.json()) .then(({ available }) => { terrainOffline = available; overlaysControl.setHillshadeOfflineAvailable(available); overlaysControl.setShadowOfflineAvailable(available); }) .catch(() => {})); ready.push(fetch("/api/hiking-trails") .then((response) => response.json()) .then(({ countries, bboxes }) => overlaysControl.setHikingTrailsOfflineCountries(countries, bboxes)) .catch(() => {})); ready.push(fetch("/api/kiwix") .then((response) => response.json()) .then(({ available }) => overlaysControl.setWikiAvailable(available)) .catch(() => {})); // What was on before the reload / update (localStorage, per device): once // the checks above are in (offline or online terrain, trails, wiki) and the // base map they switched to has loaded. Promise.allSettled(ready).then(() => { const restore = () => { overlaysControl.restore(); gpxPanel.restore(); }; if (map.loaded()) restore(); else map.once("idle", restore); }); // Right click, a long press (touch browsers fire contextmenu for it) or // Alt+click: what's here (the Design canvas' Desktop). The position on top, // a click copies it; Route here / Add to the trip / Save a point; every // rendered feature's raw properties folded under it (the debug view it // was). C copies the position under the mouse with no popup. const copyPosition = async ({ lng, lat }) => { try { await navigator.clipboard.writeText(`${lat.toFixed(6)}, ${lng.toFixed(6)}`); return true; } catch { return false; // clipboard API unavailable (an insecure context) } }; const whatsHere = (event) => { const { lngLat } = event; const features = map.queryRenderedFeatures(event.point); const rows = features .map((feature) => { const cells = Object.entries(feature.properties) .map(([key, value]) => `| (no properties) |