The standalone map viewer draws overlays, as the map does (#966)

The standalone viewer (port 8084) drew basemaps only: a map file which is
not a basemap was skipped.  It now offers each overlay in its layer panel,
hidden until turned on, with a checkbox per layer, draws it with the style
beside it when there is one, and shows a feature's attributes on a click.

The overlay logic is the map viewer's own.  It moved to dependency-free
modules (app/src/map-shared) which a browser can load as they are; the
standalone viewer, which has no build step, loads copies of them from
modules/map/static/js.  A test fails while a copy differs from its module
(`npm run sync:map-shared` makes the copies).  What differs between the
viewers is passed in: where a map file and its style are fetched from, and
whether a layer can be checked before MapLibre is given it.

The standalone viewer cannot check a layer first, so it adds an overlay's
layers to the map one at a time once the style has loaded: MapLibre refuses a
whole style over one layer it cannot draw, but only that layer when it is
added by itself.

The API also names a style by its path within the map directory, which is
what the standalone viewer is served.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-11-13 17:27:38 -07:00 • committed by Roland
parent 113e70a402
commit 177d0dba4b
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
15 changed files with 1754 additions and 506 deletions

View file

@ -56,6 +56,28 @@
.layer-group-header:hover { color: #1a73e8; }
.layer-group-header input { cursor: pointer; width: 16px; height: 16px; }
/* Overlays: map files which are not the basemap, each with its own layers. */
#overlay-section { border-top: 1px solid #eee; margin-top: 4px; padding-top: 4px; }
#overlay-section h4 { padding: 4px 14px; font-size: 13px; }
.overlay-file { display: flex; align-items: center; gap: 6px; padding: 4px 14px; }
.overlay-file label { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.overlay-file input, .overlay-layer input { cursor: pointer; width: 16px; height: 16px; }
.overlay-zooms { color: #888; font-size: 11px; }
.overlay-expand {
margin-left: auto; border: none; background: none; cursor: pointer;
font-size: 12px; color: #555; padding: 2px 4px;
}
.overlay-layers { padding: 0 14px 4px 38px; font-size: 13px; }
.overlay-layers .overlay-note { color: #888; font-size: 11px; padding: 2px 0; }
.overlay-all-none { display: flex; gap: 8px; padding: 2px 0; }
.overlay-all-none button {
border: none; background: none; cursor: pointer; padding: 0;
color: #888; font-size: 11px; text-decoration: underline;
}
.overlay-layer { display: flex; align-items: center; gap: 6px; padding: 1px 0; cursor: pointer; }
.overlay-layer.disabled { color: #aaa; }
.overlay-swatch { width: 10px; height: 10px; flex: none; border: 1px solid #ccc; }
/* File selector */
#file-panel {
position: absolute;
@ -253,6 +275,78 @@
var hasTerrain = false;
var contextMenuData = null;
// --- Overlays: map files which are not a basemap ---
// The logic is the map viewer's own (app/src/map-shared), loaded from the copies in /js/. Until
// it has loaded (or if it cannot be), this viewer draws basemaps only.
var Overlays = null;
var OverlayStyle = null;
// The overlay files; one which came with a style has `styleLayers`.
var overlayFiles = [];
// What the user chose to see: {[map_path]: {enabled, layers: {[layerId]: bool}}}.
var overlayState = {};
// Which overlay files have their layers listed in the panel.
var overlayExpanded = {};
// How many layers of each file MapLibre refused, by map_path.
var overlayRefused = {};
// This viewer is served the map directory at /data/, not the media directory.
var OVERLAY_URLS = {
pmtiles: function(file) { return "pmtiles://" + dataPath(file.map_path); },
style: function(file) { return dataPath(file.style_map_path); },
};
function loadOverlays(files) {
if (!files.length) return Promise.resolve();
return Promise.all([import("/js/overlays.js"), import("/js/overlayStyle.js")])
.then(function(modules) {
Overlays = modules[0];
OverlayStyle = modules[1];
overlayState = Overlays.loadOverlayState();
// No `validateLayer`: this viewer cannot check a layer first, so each is added to
// the map by itself (see applyOverlays).
return OverlayStyle.loadOverlayStyles(files, {urls: OVERLAY_URLS});
})
.then(function(files) { overlayFiles = files; })
.catch(function(err) {
console.error("Overlays are not available:", err);
overlayFiles = [];
});
}
// Add the overlays to the map. The style must have loaded; a new style has none of them.
function applyOverlays() {
if (!Overlays || !overlayFiles.length || !map) return;
overlayFiles.forEach(function(file) {
if (!Overlays.isStyledOverlay(file) || !file.has_sprite) return;
var id = OverlayStyle.overlaySpriteId(file);
try {
var has = (map.getSprite() || []).some(function(sprite) { return sprite.id === id; });
if (!has) map.addSprite(id, OverlayStyle.overlaySpriteUrl(file));
} catch (e) { console.warn("Could not add the icons of " + file.map_path, e); }
});
overlayRefused = Overlays.addOverlaysToMap(map, overlayFiles, overlayState, OVERLAY_URLS);
}
// Remember what the user chose to see of an overlay, and show or hide its layers to match.
function changeOverlayState(file, next) {
overlayState = next;
Overlays.saveOverlayState(next);
if (map && map.getStyle()) {
Overlays.buildOverlayLayers(file, next).forEach(function(layer) {
if (map.getLayer(layer.id)) {
map.setLayoutProperty(layer.id, "visibility", layer.layout.visibility);
}
});
}
buildLayerControls();
}
function overlayLayerIds() {
if (!Overlays || !map || !map.getStyle()) return [];
return (map.getStyle().layers || [])
.filter(function(l) { return Overlays.isOverlayLayerId(l.id) && l.type !== "raster"; })
.map(function(l) { return l.id; });
}
// Load saved state from localStorage.
function getSavedVisibility() {
try {
@ -461,6 +555,22 @@
menu.style.display = "block";
});
map.on("click", function() { document.getElementById("context-menu").style.display = "none"; });
// Click an overlay's feature to see its attributes.
map.on("click", function(e) {
var layers = overlayLayerIds();
if (!layers.length) return;
var html = Overlays.overlayPopupHtml(map.queryRenderedFeatures(e.point, {layers: layers}));
if (!html) return;
new maplibregl.Popup({offset: 8, maxWidth: "260px"}).setLngLat(e.lngLat).setHTML(html).addTo(map);
});
map.on("mousemove", function(e) {
var layers = overlayLayerIds();
var hit = layers.length && map.queryRenderedFeatures(e.point, {layers: layers}).length;
map.getCanvas().style.cursor = hit ? "pointer" : "";
});
// A layer MapLibre refuses (an overlay's style may have one) is reported, not fatal.
map.on("error", function(e) { console.warn("Map error:", e && e.error ? e.error.message : e); });
map.on("movestart", function() { document.getElementById("context-menu").style.display = "none"; });
// Long-press context menu (mobile).
@ -501,6 +611,7 @@
longPressTimer = null;
});
map.on("load", function() {
applyOverlays();
buildLayerControls();
});
}
@ -545,6 +656,8 @@
// --- Layer control ---
function matchesGroup(layerId, prefixes) {
// An overlay's layers belong to no basemap group, whatever they are named.
if (layerId.indexOf("overlay:") === 0) return false;
var baseId = layerId.indexOf(":") >= 0 ? layerId.split(":").slice(1).join(":") : layerId;
return prefixes.some(function(prefix) {
return baseId.indexOf(prefix) >= 0;
@ -589,6 +702,8 @@
container.appendChild(div);
}
buildOverlayControls(container);
// Scale unit toggle.
var scaleDiv = document.createElement("div");
scaleDiv.className = "layer-group";
@ -622,6 +737,117 @@
container.appendChild(scaleDiv);
}
function checkboxLabel(className, text, checked, onChange) {
var label = document.createElement("label");
label.className = className;
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = checked;
checkbox.addEventListener("change", function(e) { onChange(e.target.checked); });
label.appendChild(checkbox);
return {label: label, checkbox: checkbox, text: label.appendChild(document.createElement("span"))};
}
function textButton(text, onClick) {
var button = document.createElement("button");
button.type = "button";
button.textContent = text;
button.addEventListener("click", onClick);
return button;
}
// One overlay file: a checkbox for the file, and (for a vector file) one per layer behind an
// arrow. An overlay is hidden until it is turned on.
function buildOverlayControl(file) {
var label = Overlays.overlayLabel(file, overlayFiles);
var enabled = Overlays.isOverlayEnabled(overlayState, file);
var layers = Overlays.overlayToggleLayers(file);
var styled = Overlays.isStyledOverlay(file);
var expanded = !!overlayExpanded[file.map_path];
var fragment = document.createDocumentFragment();
var row = document.createElement("div");
row.className = "overlay-file";
row.title = [file.description, file.map_path].filter(Boolean).join("\n");
var fileBox = checkboxLabel("", label, enabled, function(checked) {
changeOverlayState(file, Overlays.setOverlayEnabled(overlayState, file, checked));
});
fileBox.text.textContent = label;
row.appendChild(fileBox.label);
if (isFinite(file.min_zoom) && isFinite(file.max_zoom) && file.min_zoom !== null) {
var zooms = document.createElement("span");
zooms.className = "overlay-zooms";
zooms.textContent = "z" + file.min_zoom + "\u2013" + file.max_zoom;
row.appendChild(zooms);
}
if (layers.length) {
var expand = textButton(expanded ? "\u25BC" : "\u25B6", function() {
overlayExpanded[file.map_path] = !expanded;
buildLayerControls();
});
expand.className = "overlay-expand";
expand.setAttribute("aria-label", (expanded ? "Hide" : "Show") + " layers of " + label);
expand.setAttribute("aria-expanded", expanded ? "true" : "false");
row.appendChild(expand);
}
fragment.appendChild(row);
if (!expanded || !layers.length) return fragment;
var list = document.createElement("div");
list.className = "overlay-layers";
var allNone = document.createElement("div");
allNone.className = "overlay-all-none";
allNone.appendChild(textButton("All", function() {
changeOverlayState(file, Overlays.setAllOverlayLayersEnabled(overlayState, file, true));
}));
allNone.appendChild(textButton("None", function() {
changeOverlayState(file, Overlays.setAllOverlayLayersEnabled(overlayState, file, false));
}));
list.appendChild(allNone);
// Layers of its style the map could not use: found when the style was read, or refused
// by MapLibre when added.
var skipped = (file.styleSkipped || 0) + (overlayRefused[file.map_path] || 0);
if (skipped) {
var note = document.createElement("div");
note.className = "overlay-note";
note.textContent = skipped + " style " + (skipped === 1 ? "layer" : "layers") + " skipped";
list.appendChild(note);
}
layers.forEach(function(layer) {
var box = checkboxLabel("overlay-layer" + (enabled ? "" : " disabled"), layer.id,
Overlays.isOverlayLayerEnabled(overlayState, file, layer.id), function(checked) {
changeOverlayState(file,
Overlays.setOverlayLayerEnabled(overlayState, file, layer.id, checked));
});
box.checkbox.disabled = !enabled;
if (layer.description) box.label.title = layer.description;
// A generic layer is drawn in one color; a styled one however its style says.
if (!styled) {
var swatch = document.createElement("span");
swatch.className = "overlay-swatch";
swatch.style.background = Overlays.overlayColor(layer.id);
box.label.insertBefore(swatch, box.text);
}
box.text.textContent = layer.id;
list.appendChild(box.label);
});
fragment.appendChild(list);
return fragment;
}
function buildOverlayControls(container) {
if (!Overlays || !overlayFiles.length) return;
var section = document.createElement("div");
section.id = "overlay-section";
var title = document.createElement("h4");
title.textContent = "Overlays";
section.appendChild(title);
overlayFiles.forEach(function(file) { section.appendChild(buildOverlayControl(file)); });
container.appendChild(section);
}
// Toggle layer panel
document.getElementById("layer-toggle").addEventListener("click", function() {
var content = document.getElementById("layer-content");
@ -659,6 +885,7 @@
setGroupVisibility(groupName, false);
}
}
applyOverlays();
buildLayerControls();
});
}
@ -711,6 +938,7 @@
// Separate files into planet, terrain, and regional extracts.
var planetFile = null;
var regionFiles = [];
var overlayCandidates = [];
for (var i = 0; i < allFiles.length; i++) {
var f = allFiles[i];
// A file the user ignores is not drawn.
@ -722,8 +950,11 @@
if (isTerrain) {
terrainFileName = f.mapPath;
hasTerrain = true;
} else if (f.kind === "overlay") {
// Not the basemap schema: offered in the layer panel, drawn as itself.
overlayCandidates.push(f);
} else if (f.kind && f.kind !== "basemap") {
// Overlays (and unreadable files) are not the basemap schema this viewer draws.
// An unreadable file is not drawn.
continue;
} else if (isPlanetFile(f.name)) {
if (!planetFile || f.size > planetFile.size) {
@ -739,7 +970,7 @@
// Planet covers everything — sole vector source, no overview needed.
pmtilesFiles = [planetFile.mapPath];
hasPlanetOverview = false;
return pmtilesFiles;
return loadOverlays(overlayCandidates).then(function() { return pmtilesFiles; });
}
// Use regional extracts.
@ -749,6 +980,7 @@
return fetch(MAP_OVERVIEW_URL, {method: "HEAD"})
.then(function(r) { hasPlanetOverview = r.ok; })
.catch(function() { hasPlanetOverview = false; })
.then(function() { return loadOverlays(overlayCandidates); })
.then(function() { return pmtilesFiles; });
})
.then(function(pmtilesFiles) {

View file

@ -0,0 +1,245 @@
// A style a person put beside a PMTiles file says how that overlay is drawn, in place of the generic
// colors. It is an ordinary MapLibre style document written for some other map, so only what is
// safe and meaningful here is taken from it: the layers which draw this file. Its sources, sprite
// and glyph URLs are never used, so a style cannot make the map ask another host for anything.
//
// SHARED by the map viewer of the app and the standalone viewer; see overlays.js for the rules
// this file keeps. A viewer which can check a layer before giving it to MapLibre passes
// `validateLayer(layer, sourceId, spriteId)`, which returns the layer's errors.
import {encodePath, overlaySourceId} from "./overlays.js";
// The fonts the map has glyphs for (modules/map/static/fonts). The map has one glyph URL, so a
// style's own fonts cannot be loaded; each is replaced by the nearest of these.
const FONT_REGULAR = "Noto Sans Regular";
const FONT_MEDIUM = "Noto Sans Medium";
const FONT_ITALIC = "Noto Sans Italic";
// Properties whose value names an image of the sprite.
const IMAGE_PROPERTIES = {
layout: ["icon-image"],
paint: ["fill-pattern", "line-pattern", "fill-extrusion-pattern"],
};
// Expression operators a `text-font` value can start with; anything else is a plain list of fonts.
const FONT_EXPRESSIONS = new Set(["literal", "match", "case", "step", "coalesce", "let", "var", "get"]);
export function bundledFont(name) {
if (/italic|oblique/i.test(name)) return FONT_ITALIC;
if (/bold|medium|black|heavy/i.test(name)) return FONT_MEDIUM;
return FONT_REGULAR;
}
const fontList = fonts => [...new Set(fonts.map(f => bundledFont(String(f))))];
// Inside an expression only a `literal` list is a list of fonts; other lists are not (the labels
// of a `match` are a list of strings too).
function adaptFontExpression(value) {
if (!Array.isArray(value)) return value;
if (value[0] === "literal" && Array.isArray(value[1])) return ["literal", fontList(value[1])];
return value.map(adaptFontExpression);
}
// Replace every font a `text-font` value names, as a plain list or as the literal lists of an
// expression.
function adaptFonts(value) {
if (!Array.isArray(value)) return value;
return FONT_EXPRESSIONS.has(value[0]) ? adaptFontExpression(value) : fontList(value);
}
// A `text-field` can set the font of a part of the text (the options of a `format` section); those
// fonts are replaced too.
function adaptTextFieldFonts(value) {
if (Array.isArray(value)) return value.map(adaptTextFieldFonts);
if (value && typeof value === "object") {
const options = {};
for (const [key, option] of Object.entries(value)) {
options[key] = key === "text-font" ? adaptFonts(option) : adaptTextFieldFonts(option);
}
return options;
}
return value;
}
// The id of an overlay's sprite; MapLibre knows its images as `<sprite id>:<image name>`.
export function overlaySpriteId(file) {
return overlaySourceId(file);
}
// The sprite sheet of an overlay, as MapLibre asks for it (it appends `@2x` and the extension).
export function overlaySpriteUrl(file) {
return `${window.location.origin}/api/map/files/sprite/${encodePath(file.map_path)}`;
}
const isZoom = value => Array.isArray(value) && value.length === 1 && value[0] === "zoom";
// An image may be named by a property function (the older form of an expression: an object with
// `stops`, or `type: "identity"`). It is rewritten as the expression which gives the same name,
// so that the name can be pointed at the overlay's sprite. Returns undefined for a function
// this does not know how to rewrite.
function imageFunctionExpression(fn) {
const fallback = typeof fn.default === "string" ? fn.default : "";
if (fn.type === "identity" && typeof fn.property === "string") {
return ["coalesce", ["get", fn.property], fallback];
}
const stops = fn.stops;
if (!Array.isArray(stops) || !stops.length || !stops.every(i => Array.isArray(i) && i.length === 2)) {
return undefined;
}
const inputs = stops.map(i => i[0]);
const outputs = stops.map(i => i[1]);
if (!outputs.every(i => typeof i === "string")) return undefined;
if (fn.type === "categorical") {
// One name per value of the property.
const labels = inputs.every(i => typeof i === "string") || inputs.every(i => typeof i === "number");
if (typeof fn.property !== "string" || !labels || new Set(inputs).size !== inputs.length) return undefined;
return ["match", ["get", fn.property], ...stops.flat(), fallback];
}
if (fn.type !== undefined && fn.type !== "interval") return undefined;
if (!inputs.every(i => typeof i === "number") || inputs.some((v, i) => i > 0 && v <= inputs[i - 1])) {
return undefined;
}
// A single stop is one name, whatever the input.
if (stops.length === 1) return outputs[0];
// One name per range of the zoom, or of a numeric property; below the first stop is the first.
const input = fn.property === undefined ? ["zoom"]
: typeof fn.property === "string" ? ["to-number", ["get", fn.property], inputs[0]] : undefined;
if (!input) return undefined;
return ["step", input, outputs[0], ...stops.slice(1).flat()];
}
// Point an image name at the overlay's sprite. The value is wrapped, not rewritten: the strings of
// an expression are not all image names (the labels of a `match` are not), but whatever it
// evaluates to is. An empty name stays empty: no image. Returns undefined when the value is one
// this cannot point at the sprite.
function adaptImage(value, spriteId) {
if (typeof value === "string") {
return value ? `${spriteId}:${value}` : value;
}
if (value && typeof value === "object" && !Array.isArray(value)) {
const expression = imageFunctionExpression(value);
return expression === undefined ? undefined : adaptImage(expression, spriteId);
}
if (!Array.isArray(value)) return undefined;
if (value[0] === "step" && isZoom(value[1])) {
// The zoom may only be the input of the outermost expression, so each name it chooses
// between is wrapped, not the whole.
const adapted = value.map((part, index) =>
(index >= 2 && index % 2 === 0) ? adaptImage(part, spriteId) : part);
return adapted.includes(undefined) ? undefined : adapted;
}
return ["image", ["let", "wrolpi_image", ["to-string", value],
["case", ["==", ["var", "wrolpi_image"], ""], "",
["concat", `${spriteId}:`, ["var", "wrolpi_image"]]]]];
}
// The source of the style which is this file: the one the style names for us, else the one most of
// the layers which draw this file's layers use.
function chooseSource(style, fileLayerIds) {
const named = style.metadata?.["wrolpi:source"];
if (named) return named;
const counts = {};
for (const layer of style.layers) {
if (layer && layer.source && fileLayerIds.has(layer["source-layer"])) {
counts[layer.source] = (counts[layer.source] || 0) + 1;
}
}
return Object.keys(counts).sort((a, b) => counts[b] - counts[a])[0];
}
// Turn a style written for another map into the layers which draw `file` on this one.
// Returns {layers, skipped}: `skipped` counts the layers of this file which were not usable.
export function adaptOverlayStyle(style, file, {validateLayer} = {}) {
if (!style || !Array.isArray(style.layers)) return {layers: [], skipped: 0};
const fileLayerIds = new Set((file.vector_layers || []).map(l => l.id));
const styleSource = chooseSource(style, fileLayerIds);
const source = overlaySourceId(file);
const spriteId = overlaySpriteId(file);
// A style drawn for one scale (a printed map, say) is unreadable zoomed out; it can say the zoom
// it is meant to be seen from.
const minZoom = Number(style.metadata?.["wrolpi:minzoom"]);
const layers = [];
const ids = new Set();
let skipped = 0;
for (const original of style.layers) {
// Only layers which draw this file: not the background, nor another source (hillshade, contours).
if (!original || original.source !== styleSource || !fileLayerIds.has(original["source-layer"])) continue;
const layer = JSON.parse(JSON.stringify(original));
layer.id = `${source}:${layer["source-layer"]}:${original.id}`;
layer.source = source;
if (Number.isFinite(minZoom) && minZoom > (layer.minzoom || 0)) {
layer.minzoom = minZoom;
}
if (layer.layout?.["text-font"] !== undefined) {
layer.layout["text-font"] = adaptFonts(layer.layout["text-font"]);
}
if (layer.layout?.["text-field"] !== undefined) {
layer.layout["text-field"] = adaptTextFieldFonts(layer.layout["text-field"]);
// MapLibre's own default font is not one the map has.
if (layer.layout["text-font"] === undefined) {
layer.layout["text-font"] = [FONT_REGULAR];
}
}
for (const [group, properties] of Object.entries(IMAGE_PROPERTIES)) {
for (const property of properties) {
if (layer[group]?.[property] === undefined) continue;
// Without a sprite sheet there are no images to draw. An image this cannot point at
// the overlay's sprite would be looked for in the basemap's; the layer is drawn
// without it (its text still is).
const image = file.has_sprite ? adaptImage(layer[group][property], spriteId) : undefined;
if (image === undefined) {
delete layer[group][property];
} else {
layer[group][property] = image;
}
}
}
// One bad layer must not stop the map: MapLibre refuses a whole style over it.
let errors = [];
if (validateLayer) {
try {
errors = validateLayer(layer, source, spriteId) || [];
} catch (e) {
errors = [e];
}
}
if (errors.length || ids.has(layer.id)) {
skipped += 1;
continue;
}
ids.add(layer.id);
layers.push(layer);
}
return {layers, skipped};
}
// Fetch and adapt the style beside an overlay file. Returns null when the file has none, or it
// cannot be used; the overlay is then drawn generically.
export async function loadOverlayStyle(file, {urls, validateLayer} = {}) {
if (!file.style_path) return null;
try {
const response = await fetch(urls.style(file));
if (!response.ok) return null;
const adapted = adaptOverlayStyle(await response.json(), file, {validateLayer});
return adapted.layers.length ? adapted : null;
} catch (e) {
console.error(`Could not use the style of ${file.map_path}:`, e);
return null;
}
}
// Attach its style to each overlay file which has one (`styleLayers`, `styleSkipped`).
export async function loadOverlayStyles(overlays, options) {
return Promise.all((overlays || []).map(async file => {
const adapted = await loadOverlayStyle(file, options);
return adapted ? {...file, styleLayers: adapted.layers, styleSkipped: adapted.skipped} : file;
}));
}

View file

@ -0,0 +1,329 @@
// Which map files a viewer draws, and how it draws the ones that are not a Protomaps basemap.
//
// SHARED by the map viewer of the app and the standalone viewer (modules/map/static/index.html),
// which loads the copy in modules/map/static/js/. It must stay a plain ES module a browser can
// load as it is: no imports from packages, and relative imports with their `.js`. After changing
// it, run `npm run sync:map-shared`; a test fails while the copy differs.
//
// What differs between the viewers is passed in as `urls`: `{pmtiles(file), style(file)}`, the
// URL of an overlay's PMTiles file (`pmtiles://...`) and of the style beside it.
//
// The API says what each PMTiles file is (`kind`): a `basemap` is drawn with the basemap theme,
// `terrain` becomes hillshade and contours, and an `overlay` is any other vector or raster file.
// An overlay has no style of its own, so its layers are drawn generically: one color per layer,
// as fills, lines or circles.
export function escapeHtml(value) {
return String(value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
// Every MapLibre source and layer of an overlay starts with this, so the basemap's layer groups
// (which match layer names like "water") never touch them.
export const OVERLAY_PREFIX = "overlay:";
export const STORAGE_KEY_OVERLAYS = "wrolpi-map-overlays";
const RASTER_SUFFIX = "raster";
const VECTOR_TYPES = ["fill", "line", "circle"];
// Readable on both the light and dark basemaps.
const OVERLAY_COLORS = [
"#e6194b", "#3cb44b", "#4363d8", "#f58231", "#b455e0", "#17a2a2",
"#f032e6", "#b07a3b", "#d1495b", "#8a9a1b", "#5b7fff", "#e6a700",
];
const POPUP_MAX_FEATURES = 3;
const POPUP_MAX_PROPERTIES = 12;
// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles".
export function isPlanetFile(name) {
if (name.startsWith("planet-")) return true;
return /^\d{8}\.pmtiles$/.test(name);
}
// A path as part of a URL: each of its parts is encoded (a `#` or `?` in a file name would
// otherwise end the path).
export function encodePath(path) {
return String(path).split("/").map(encodeURIComponent).join("/");
}
// Sort the map files into what the viewer does with each. Ignored files (`visible: false`) and
// unreadable files are left out. A planet file covers everything, so it replaces the regional
// extracts; overlays and terrain are drawn either way.
export function planMapFiles(files) {
const visible = (files || []).filter(f => f.visible !== false);
const basemaps = visible.filter(f => f.kind === "basemap");
let planet = null;
for (const f of basemaps) {
if (isPlanetFile(f.name) && (!planet || f.size > planet.size)) planet = f;
}
const terrains = visible.filter(f => f.kind === "terrain");
return {
planet,
regions: planet ? [] : basemaps,
terrain: terrains.length ? terrains[terrains.length - 1] : null,
overlays: visible.filter(f => f.kind === "overlay"),
};
}
export function isRasterOverlay(file) {
return file.tile_type !== "mvt";
}
// Whether the overlay is drawn with a style which came beside the file (see mapOverlayStyle.js).
export function isStyledOverlay(file) {
return !isRasterOverlay(file) && Array.isArray(file.styleLayers) && file.styleLayers.length > 0;
}
// The layers of a vector overlay the user can show and hide: all of them, or with its own style
// only those the style draws.
export function overlayToggleLayers(file) {
if (isRasterOverlay(file)) return [];
const layers = file.vector_layers || [];
if (!isStyledOverlay(file)) return layers;
const drawn = new Set(file.styleLayers.map(l => l["source-layer"]));
return layers.filter(l => drawn.has(l.id));
}
function fileStem(name) {
return String(name).replace(/\.pmtiles$/, "");
}
// What to call an overlay: the name the file gives itself, else its file name. Files which would
// share a label also show where they are.
export function overlayLabel(file, files = []) {
const base = f => (f.title && f.title.trim()) || fileStem(f.name);
const label = base(file);
const shared = files.some(f => f.map_path !== file.map_path && base(f) === label);
return shared ? `${label} (${file.map_path})` : label;
}
// A stable color for a layer: the same layer name is the same color in every file and session.
export function overlayColor(layerId) {
let hash = 5381;
for (const c of String(layerId)) hash = ((hash * 33) ^ c.charCodeAt(0)) >>> 0;
return OVERLAY_COLORS[hash % OVERLAY_COLORS.length];
}
// --- What the user chose to see. {[map_path]: {enabled: bool, layers: {[layerId]: bool}}} ---
export function loadOverlayState() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY_OVERLAYS));
if (saved && typeof saved === "object" && !Array.isArray(saved)) return saved;
} catch (e) { /* ignore */ }
return {};
}
export function saveOverlayState(state) {
try { localStorage.setItem(STORAGE_KEY_OVERLAYS, JSON.stringify(state)); } catch (e) { /* ignore */ }
}
// An overlay is hidden until the user turns it on.
export function isOverlayEnabled(state, file) {
return state?.[file.map_path]?.enabled === true;
}
// Once a file is on, each of its layers is drawn until the user turns that layer off.
export function isOverlayLayerEnabled(state, file, layerId) {
return state?.[file.map_path]?.layers?.[layerId] !== false;
}
export function setOverlayEnabled(state, file, enabled) {
return {...state, [file.map_path]: {...state?.[file.map_path], enabled}};
}
export function setOverlayLayerEnabled(state, file, layerId, enabled) {
const entry = state?.[file.map_path] || {};
return {...state, [file.map_path]: {...entry, layers: {...entry.layers, [layerId]: enabled}}};
}
export function setAllOverlayLayersEnabled(state, file, enabled) {
const layers = {};
for (const l of overlayToggleLayers(file)) layers[l.id] = enabled;
return {...state, [file.map_path]: {...state?.[file.map_path], layers}};
}
// --- MapLibre style ---
export function overlaySourceId(file) {
return `${OVERLAY_PREFIX}${file.map_path}`;
}
export function isOverlayLayerId(layerId) {
return String(layerId).startsWith(OVERLAY_PREFIX);
}
// MapLibre puts a source's attribution in the page as HTML, and this text comes from a file
// someone downloaded: only its text is kept.
function attributionText(attribution) {
if (!attribution) return undefined;
const text = new DOMParser().parseFromString(String(attribution), "text/html").body.textContent || "";
return text.trim() ? escapeHtml(text.trim()) : undefined;
}
export function buildOverlaySource(file, urls) {
const source = {type: isRasterOverlay(file) ? "raster" : "vector", url: urls.pmtiles(file)};
if (isRasterOverlay(file)) source.tileSize = 256;
const attribution = attributionText(file.attribution);
if (attribution) source.attribution = attribution;
return source;
}
// The geometry a generator recorded for a layer ("Point", "LineString", "Polygon") names the one
// way to draw it. Without that, the layer is drawn all three ways, each limited to its geometry.
const TYPE_OF_GEOMETRY = {Polygon: "fill", LineString: "line", Point: "circle"};
const GEOMETRY_OF_TYPE = {fill: "Polygon", line: "LineString", circle: "Point"};
function paintOf(type, color) {
if (type === "fill") return {"fill-color": color, "fill-opacity": 0.25, "fill-outline-color": color};
if (type === "line") return {"line-color": color, "line-width": 1.5};
return {
"circle-color": color, "circle-radius": 4,
"circle-stroke-color": "#ffffff", "circle-stroke-width": 1,
};
}
// The style layers of an overlay file, each already visible or hidden as `state` says; a source
// with no visible layer requests no tiles.
export function buildOverlayLayers(file, state) {
const source = overlaySourceId(file);
const enabled = isOverlayEnabled(state, file);
const visibility = on => (on ? "visible" : "none");
if (isRasterOverlay(file)) {
return [{
id: `${source}:${RASTER_SUFFIX}`, type: "raster", source,
layout: {visibility: visibility(enabled)},
}];
}
if (isStyledOverlay(file)) {
// The file came with its own style: its layers, each shown when the file and its source
// layer are on (and the style does not itself hide it).
return file.styleLayers.map(layer => ({
...layer,
layout: {
...layer.layout,
visibility: visibility(enabled && layer.layout?.visibility !== "none"
&& isOverlayLayerEnabled(state, file, layer["source-layer"])),
},
}));
}
const styleLayers = [];
for (const layer of file.vector_layers || []) {
const color = overlayColor(layer.id);
const known = TYPE_OF_GEOMETRY[layer.geometry];
for (const type of known ? [known] : VECTOR_TYPES) {
const styleLayer = {
id: `${source}:${layer.id}:${type}`,
type,
source,
"source-layer": layer.id,
layout: {visibility: visibility(enabled && isOverlayLayerEnabled(state, file, layer.id))},
paint: paintOf(type, color),
};
if (!known) styleLayer.filter = ["==", "$type", GEOMETRY_OF_TYPE[type]];
styleLayers.push(styleLayer);
}
}
return styleLayers;
}
// The style layers of every overlay, in the order they are drawn. A raster overlay goes under the
// basemap's labels (`rasters`) so the map stays readable; vector overlays go on top (`vectors`): an
// overlay with its own style in that style's order, then the generic ones, fills under lines under
// points.
export function orderOverlayLayers(overlays, state) {
const rasters = [];
const styled = [];
const generic = {fill: [], line: [], circle: []};
for (const file of overlays || []) {
const layers = buildOverlayLayers(file, state);
if (isStyledOverlay(file)) {
styled.push(...layers);
continue;
}
for (const layer of layers) {
if (layer.type === "raster") rasters.push(layer);
else generic[layer.type].push(layer);
}
}
return {rasters, vectors: [...styled, ...generic.fill, ...generic.line, ...generic.circle]};
}
// Add the overlays to a style's sources and layers (the basemap's are already there).
export function addOverlaysToStyle(styleSources, allLayers, overlays, state, urls) {
for (const file of overlays || []) {
styleSources[overlaySourceId(file)] = buildOverlaySource(file, urls);
}
const {rasters, vectors} = orderOverlayLayers(overlays, state);
const firstLabel = allLayers.findIndex(l => l.type === "symbol");
allLayers.splice(firstLabel === -1 ? allLayers.length : firstLabel, 0, ...rasters);
allLayers.push(...vectors);
}
// Add the overlays to a map whose style has loaded, a layer at a time. For a viewer which cannot
// check a layer before giving it to MapLibre: MapLibre refuses a whole style over one layer it
// cannot draw, but refuses only that layer when it is added by itself.
// Returns how many layers of each file (by `map_path`) were refused.
export function addOverlaysToMap(map, overlays, state, urls) {
const refused = {};
for (const file of overlays || []) {
const id = overlaySourceId(file);
if (!map.getSource(id)) map.addSource(id, buildOverlaySource(file, urls));
}
const firstLabel = (map.getStyle()?.layers || []).find(l => l.type === "symbol");
const {rasters, vectors} = orderOverlayLayers(overlays, state);
const add = (layer, before) => {
if (map.getLayer(layer.id)) return;
try {
map.addLayer(layer, before);
} catch (e) { /* refused; counted below */ }
if (!map.getLayer(layer.id)) {
const mapPath = (overlays || []).find(f => layer.source === overlaySourceId(f))?.map_path;
refused[mapPath] = (refused[mapPath] || 0) + 1;
}
};
for (const layer of rasters) add(layer, firstLabel?.id);
for (const layer of vectors) add(layer, undefined);
return refused;
}
// --- Popup ---
// The popup HTML of the overlay features under a click, or null when there are none. An overlay's
// attributes are whatever its author chose, so they are listed as they are.
export function overlayPopupHtml(features) {
const seen = new Set();
const blocks = [];
for (const feature of features || []) {
const layerId = feature.sourceLayer || feature.layer?.["source-layer"];
const properties = feature.properties || {};
if (!layerId) continue;
const key = JSON.stringify([layerId, properties]);
if (seen.has(key)) continue;
seen.add(key);
if (blocks.length >= POPUP_MAX_FEATURES) break;
const entries = Object.entries(properties).filter(([, v]) => v !== null && v !== undefined && v !== "");
const name = properties.name;
const rows = entries
.filter(([k]) => k !== "name")
.slice(0, POPUP_MAX_PROPERTIES)
.map(([k, v]) => `<br/><small>${escapeHtml(k)}: ${escapeHtml(v)}</small>`);
const more = entries.length - (name !== undefined ? 1 : 0) - rows.length;
blocks.push(
`<div style="font-size:13px">` +
`<strong>${escapeHtml(name !== undefined && name !== "" ? name : layerId)}</strong>` +
(name !== undefined && name !== "" ? `<br/><small>${escapeHtml(layerId)}</small>` : "") +
rows.join("") +
(more > 0 ? `<br/><small>… ${more} more</small>` : "") +
`</div>`
);
}
return blocks.length ? blocks.join('<hr style="margin:4px 0"/>') : null;
}