From ad2223f427f453abef95eaebe40f041e91997346 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 15 Nov 2026 13:26:45 -0700 Subject: [PATCH] Give trail pages an outdoor map Trail maps now open on an outdoor style of our own, drawn on the same OpenFreeMap tiles: hill shading and contour lines from the public Terrain Tiles, woods, water, footpaths, and peaks with their heights. Heights and contours follow the visitor's units. A switch on the map goes back to the plain map and is remembered. The home page's overview map is unchanged. If the elevation tiles or the contour script fail, the map still loads without them. The security policy allows the one elevation-tile path. The contour add-on (maplibre-contour 0.1.1) is vendored with its licence, and the elevation data is credited on the map, under it and in the footer. Co-Authored-By: Claude Fable 5.2 --- web/assets/app.js | 236 +++++++++++++++- web/assets/map/LICENSE.txt | 73 +++++ web/assets/map/outdoor.json | 256 ++++++++++++++++++ web/assets/prefs.js | 5 +- web/assets/style.css | 16 ++ web/assets/vendor/README.md | 41 ++- .../vendor/maplibre-contour/LICENSE.txt | 72 +++++ .../maplibre-contour/maplibre-contour.js | 15 + web/olt/common.py | 24 ++ web/olt/layout.py | 16 +- web/olt/pages.py | 2 +- web/olt/trail.py | 9 +- web/static/_headers | 16 +- web/tests/test_extra.py | 15 + web/tests/test_outdoor_map.py | 225 +++++++++++++++ 15 files changed, 994 insertions(+), 27 deletions(-) create mode 100644 web/assets/map/LICENSE.txt create mode 100644 web/assets/map/outdoor.json create mode 100644 web/assets/vendor/maplibre-contour/LICENSE.txt create mode 100644 web/assets/vendor/maplibre-contour/maplibre-contour.js create mode 100644 web/tests/test_outdoor_map.py diff --git a/web/assets/app.js b/web/assets/app.js index 3f72877..45f5f36 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -1,9 +1,11 @@ /* Site script, served at /assets/app.js (deferred). Vanilla JS, no build step. - 1. Preferences: theme and length order (saved in localStorage; applied early by prefs.js) + 1. Preferences: theme, length order and base map (saved in localStorage; applied + early by prefs.js) 2. Maps: .mapfig[data-map] figures. Data is fetched from data-src (same origin); lines are drawn on a plain graticule first, then on an OpenFreeMap base map - when MapLibre and WebGL are available. + when MapLibre and WebGL are available. A trail page's map (data-outdoor) is + an outdoor map, with relief and contours, and a switch to the plain one. 3. Trail finder (home page): search, filters, sort, URL query state, map/list highlight 4. Copy-credit buttons @@ -50,6 +52,16 @@ document.dispatchEvent(new Event('olt:units')); } + /* The base map of the trail maps: 'outdoor' (the default) or 'plain'. */ + function basemapChoice() { return root.dataset.basemap === 'plain' ? 'plain' : 'outdoor'; } + + function setBasemap(value) { + if (value === 'plain') root.dataset.basemap = 'plain'; + else delete root.dataset.basemap; + writePref('lh-basemap', value === 'plain' ? 'plain' : null); + document.dispatchEvent(new Event('olt:basemap')); + } + function syncRadios(selector, value) { document.querySelectorAll(selector).forEach(function (input) { input.checked = input.value === value; }); } @@ -89,6 +101,137 @@ var STYLE_URL = 'https://tiles.openfreemap.org/styles/positron'; + /* The outdoor base map of a trail page: the style named by the figure's + data-outdoor (web/assets/map/outdoor.json), with relief from its olt-dem + elevation source and contour lines made in the browser by maplibre-contour + (window.mlcontour, loaded after MapLibre on trail pages only). Each layer + carries its own dark-theme paint (metadata "olt:dark") and its layout for + a reader who puts km and m first (metadata "olt:km"); the contour steps for + each unit are in the style's metadata "olt:contours". Relief and contours + are extras: they stay hidden until the map is ready, so a slow or blocked + elevation host never holds the map up, and their errors never fail it. */ + var ELEVATION = { 'olt-dem': true, 'olt-contours': true }; + var outdoorStyles = {}; + var demSource; + + function fetchOutdoor(url) { + if (!outdoorStyles[url]) { + outdoorStyles[url] = fetch(url, { credentials: 'same-origin' }) + .then(function (r) { + if (!r.ok) throw new Error(r.status); + return r.json(); + }) + .catch(function () { return null; }); + } + return outdoorStyles[url]; + } + + /* One elevation tile source for the page, shared by the relief and the + contours; null when the add-on is missing (relief only, then). */ + function contourSource(dem) { + if (demSource !== undefined) return demSource; + demSource = null; + if (window.mlcontour && window.mlcontour.DemSource) { + try { + demSource = new window.mlcontour.DemSource({ + url: dem.tiles[0], encoding: dem.encoding, maxzoom: dem.maxzoom, worker: true, timeoutMs: 10000 + }); + demSource.setupMaplibre(window.maplibregl); + } catch (e) { demSource = null; } + } + return demSource; + } + + function contourUrl(base) { + var opts = base.metadata['olt:contours'][milesFirst() ? 'ft' : 'm']; + return demSource.contourProtocolUrl({ multiplier: opts.multiplier, thresholds: opts.thresholds }); + } + + function assign(target, values) { + Object.keys(values).forEach(function (k) { target[k] = values[k]; }); + return target; + } + + /* The style to hand MapLibre: the file in the reader's theme and units, its + elevation tiles fetched through the add-on when it is here. */ + function outdoorStyle(base, hideElevation) { + var style = JSON.parse(JSON.stringify(base)); + var dark = isDark(); + var km = !milesFirst(); + var dem = style.sources['olt-dem']; + var contours = dem ? contourSource(dem) : null; + if (contours) { + dem.tiles = [contours.sharedDemProtocolUrl]; + style.sources['olt-contours'].tiles = [contourUrl(base)]; + } else { + delete style.sources['olt-contours']; + style.layers = style.layers.filter(function (layer) { return layer.source !== 'olt-contours'; }); + } + style.layers.forEach(function (layer) { + var meta = layer.metadata || {}; + if (dark && meta['olt:dark']) layer.paint = assign(layer.paint || {}, meta['olt:dark']); + if (km && meta['olt:km']) layer.layout = assign(layer.layout || {}, meta['olt:km']); + if (hideElevation && ELEVATION[layer.source]) layer.layout = assign(layer.layout || {}, { visibility: 'none' }); + }); + return style; + } + + /* A theme or units change on a live outdoor map: the same metadata, set + layer by layer (MapLibre skips a value that is already set). */ + function restyleOutdoor(map, base) { + var dark = isDark(); + var km = !milesFirst(); + base.layers.forEach(function (layer) { + if (!map.getLayer(layer.id)) return; + var night = (layer.metadata || {})['olt:dark'] || {}; + var metric = (layer.metadata || {})['olt:km'] || {}; + Object.keys(night).forEach(function (prop) { + map.setPaintProperty(layer.id, prop, dark ? night[prop] : (layer.paint || {})[prop]); + }); + Object.keys(metric).forEach(function (prop) { + map.setLayoutProperty(layer.id, prop, km ? metric[prop] : (layer.layout || {})[prop]); + }); + }); + } + + function showElevation(map) { + map.getStyle().layers.forEach(function (layer) { + if (ELEVATION[layer.source]) map.setLayoutProperty(layer.id, 'visibility', 'visible'); + }); + } + + /* The Outdoor / Plain switch: a MapLibre control of two toggle buttons, top + left, clear of the zoom buttons, the scale bar and the credits. */ + function basemapControl() { + var box; + function sync() { + var choice = basemapChoice(); + box.querySelectorAll('button').forEach(function (b) { + b.setAttribute('aria-pressed', b.dataset.basemap === choice ? 'true' : 'false'); + }); + } + return { + sync: sync, + onAdd: function () { + box = document.createElement('div'); + box.className = 'maplibregl-ctrl maplibregl-ctrl-group basemap-switch'; + box.setAttribute('role', 'group'); + box.setAttribute('aria-label', 'Base map'); + [['outdoor', 'Outdoor'], ['plain', 'Plain']].forEach(function (pair) { + var b = document.createElement('button'); + b.type = 'button'; + b.dataset.basemap = pair[0]; + b.textContent = pair[1]; + b.addEventListener('click', function () { if (basemapChoice() !== pair[0]) setBasemap(pair[0]); }); + box.appendChild(b); + }); + sync(); + return box; + }, + onRemove: function () { if (box.parentNode) box.parentNode.removeChild(box); } + }; + } + function linesOf(feature) { var g = feature.geometry || {}; if (g.type === 'LineString') return [g.coordinates]; @@ -311,7 +454,9 @@ } if (kind === 'sketch') { var col = routeMain ? '--route' : '--trail'; + /* A pale band under the dots lifts them off relief and contours. */ return [ + { id: 'olt-sketch-halo', color: '--casing', width: [5, 6, 12, 9], opacity: 0.6, filter: IS_SKETCH }, { id: 'olt-sketch', color: col, width: [5, 3, 12, 5], dash: [0, 2], cap: 'round', filter: IS_SKETCH }, { id: 'olt-sketch-points', type: 'circle', stroke: col, strokeWidth: 2.5, radius: [5, 5, 12, 8], filter: IS_SKETCH } ]; @@ -329,9 +474,10 @@ return token(def.stroke || '--trail'); } - /* Trail lines go under the base map's labels, as on a printed map. */ + /* Trail lines go under the base map's labels, as on a printed map (and over + the contour labels, which sit with their lines below the water). */ function addLineLayers(map, fc, defs) { - var firstLabel = map.getStyle().layers.filter(function (l) { return l.type === 'symbol'; })[0]; + var firstLabel = map.getStyle().layers.filter(function (l) { return l.type === 'symbol' && !ELEVATION[l.source]; })[0]; map.addSource('olt', { type: 'geojson', data: fc }); defs.forEach(function (def) { var layer; @@ -357,6 +503,7 @@ } }; if (def.dash) layer.paint['line-dasharray'] = def.dash; + if (def.opacity) layer.paint['line-opacity'] = def.opacity; } if (def.filter) layer.filter = def.filter; map.addLayer(layer, firstLabel && firstLabel.id); @@ -376,6 +523,9 @@ var routeMain = fig.dataset.route === 'yes'; var defs = layerDefs(kind, routeMain); var onlyIds = (fig.dataset.ids || '').trim().split(/\s+/).filter(Boolean); + /* A trail page's map: fetch its outdoor style now, beside the track data. */ + var outdoorUrl = kind === 'overview' ? '' : (fig.dataset.outdoor || ''); + if (outdoorUrl) fetchOutdoor(outdoorUrl); var entry = { kind: kind, map: null, fc: null, defs: defs, fallback: fallback, visibleIds: onlyIds.length ? onlyIds : null, ready: false, mapStarted: false, fullBounds: null, boundsById: null }; @@ -450,10 +600,22 @@ if (!window.maplibregl) { dataReady.then(function (fc) { if (fc) fail('the map library did not load'); }); return; } if (!webglAvailable()) { dataReady.then(function (fc) { if (fc) fail('WebGL is off in this browser'); }); return; } if (!entry.ready && entry.fc) status.textContent = 'Loading the base map…'; + var timer = setTimeout(function () { fail('tiles did not load'); }, 15000); + if (outdoorUrl) fetchOutdoor(outdoorUrl).then(function (base) { createMap(base, timer); }); + else createMap(null, timer); + } + /* base: the outdoor style of a trail map, or null for a map with the plain + style only (the overview maps, or when the style file did not load). */ + function createMap(base, timer) { + var current = base && basemapChoice() === 'outdoor' ? 'outdoor' : 'plain'; + var contourMiles = milesFirst(); /* the units the contour tiles are made in */ + var settled = false; /* the current style is loaded and dressed */ + var styleGen = 0; + var switcher = null; var options = { container: host.querySelector('.map__canvas'), - style: STYLE_URL, + style: current === 'outdoor' ? outdoorStyle(base, true) : STYLE_URL, attributionControl: { compact: true }, cooperativeGestures: true, dragRotate: false, @@ -472,6 +634,7 @@ map.addControl(scale, 'bottom-left'); document.addEventListener('olt:units', function () { scale.setUnit(milesFirst() ? 'imperial' : 'metric'); + if (settled && current === 'outdoor') restyle(); }); /* A narrow frame has no room for the open attribution beside the scale @@ -486,38 +649,89 @@ map.on('resize', collapseAttribution); var originals = {}; - var timer = setTimeout(function () { fail('tiles did not load'); }, 15000); - map.on('error', function () { if (!map.isStyleLoaded()) fail('the map style did not load'); }); + map.on('error', function (e) { + if (e && e.sourceId && ELEVATION[e.sourceId]) return; /* no relief or contours here: the map stands */ + if (!map.isStyleLoaded()) fail('the map style did not load'); + }); + + /* The outdoor style in the reader's theme and units; contour tiles are + remade only when the units change. */ + function restyle() { + restyleOutdoor(map, base); + var source = map.getSource('olt-contours'); + if (source && demSource && contourMiles !== milesFirst()) { + contourMiles = milesFirst(); + source.setTiles([contourUrl(base)]); + } + } + + /* A freshly loaded base map: the theme, then the trail on top. */ + function dress() { + if (current === 'plain') { + originals = {}; + tintBasemap(map, originals); + } else { + restyle(); + } + addLineLayers(map, entry.fc, defs); + } var styleReady = new Promise(function (resolve) { map.on('load', resolve); }); Promise.all([dataReady, styleReady]).then(function (results) { var fc = results[0]; if (!fc) return; clearTimeout(timer); - tintBasemap(map, originals); - addLineLayers(map, fc, defs); + dress(); if (!bbox) { bbox = bboxOf(fc); entry.fullBounds = bbox.slice(); map.fitBounds([[bbox[0], bbox[1]], [bbox[2], bbox[3]]], { padding: 32, animate: false }); } entry.ready = true; + settled = true; host.dataset.state = 'ready'; status.textContent = ''; collapseAttribution(); if (entry.visibleIds) setVisible(entry, entry.visibleIds); if (kind === 'overview') wireOverview(map, defs); + if (current === 'outdoor') showElevation(map); + if (base) { + switcher = basemapControl(); + map.addControl(switcher, 'top-left'); + } mapCorners(); }); + /* Outdoor <-> Plain. setStyle drops every added layer, so the trail is + drawn again on the new style, with the theme, the units and the + visible-ids filter; the camera stays where the reader left it. */ + function applyBasemap() { + if (switcher) switcher.sync(); + var want = base && basemapChoice() === 'outdoor' ? 'outdoor' : 'plain'; + if (!entry.ready || want === current) return; + current = want; + settled = false; + var gen = ++styleGen; + if (want === 'outdoor') contourMiles = milesFirst(); + map.setStyle(want === 'outdoor' ? outdoorStyle(base, false) : STYLE_URL, { diff: false }); + map.once('style.load', function () { + if (gen !== styleGen) return; /* a later switch replaced this style */ + dress(); + if (entry.visibleIds) setVisible(entry, entry.visibleIds); + settled = true; + }); + } + if (base) document.addEventListener('olt:basemap', applyBasemap); + function mapCorners() { var b = map.getBounds(); corners({ w: b.getWest(), e: b.getEast(), n: b.getNorth(), s: b.getSouth() }); } map.on('moveend', function () { if (entry.ready) mapCorners(); }); document.addEventListener('olt:theme', function () { - if (!entry.ready) return; - tintBasemap(map, originals); + if (!entry.ready || !settled) return; /* a style still loading is dressed in the new theme */ + if (current === 'outdoor') restyle(); + else tintBasemap(map, originals); defs.forEach(function (def) { if (def.type === 'circle') { map.setPaintProperty(def.id, 'circle-color', token('--casing')); diff --git a/web/assets/map/LICENSE.txt b/web/assets/map/LICENSE.txt new file mode 100644 index 0000000..8f0ff45 --- /dev/null +++ b/web/assets/map/LICENSE.txt @@ -0,0 +1,73 @@ +outdoor.json, the outdoor map style of the trail pages, is derived from the +Liberty style of OpenFreeMap (https://github.com/hyperknot/openfreemap-styles), +read 2026-11-15. Liberty is a fork of OSM Liberty +(https://github.com/maputnik/osm-liberty), which is a fork of OSM Bright +(https://github.com/openmaptiles/osm-bright-gl-style), derived from Mapbox Open +Styles. The notices of each follow. + +The map design (look and feel) of OpenMapTiles styles is under the Creative +Commons Attribution 4.0 licence (https://creativecommons.org/licenses/by/4.0/). +It is credited in the corner of every map as "© OpenMapTiles", linked to +https://www.openmaptiles.org/, beside "© OpenStreetMap" for the map data. + +The elevation, relief and contour parts (the olt-dem and olt-contours sources +and the hillshade and contour layers) and the colours are this site's own. + +------------------------------------------------------------------------------- +OpenFreeMap styles: MIT License + +Copyright (c) 2023 Zsolt Ero + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------- +OSM Liberty and OSM Bright: BSD 3-Clause License (code) + +Copyright (c) 2024, MapTiler.com & OpenMapTiles contributors. +Copyright (c) 2014, Mapbox. +All rights reserved. + +Modifications by MapTiler.com & OpenMapTiles contributors, by the OSM Liberty +contributors and by OpenFreeMap. Derived from "Mapbox Open Styles" +https://github.com/mapbox/mapbox-gl-styles + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/web/assets/map/outdoor.json b/web/assets/map/outdoor.json new file mode 100644 index 0000000..4103961 --- /dev/null +++ b/web/assets/map/outdoor.json @@ -0,0 +1,256 @@ +{ + "version": 8, + "name": "Long Hikes outdoor", + "metadata": { + "olt:about": "The outdoor base map of the trail pages, read by /assets/app.js. Derived from OpenFreeMap Liberty (MIT), itself a fork of OSM Liberty and OSM Bright (BSD-3-Clause code, CC BY 4.0 design); see LICENSE.txt beside this file. Light colours are in each layer's paint; olt:dark holds the same layer's dark-theme paint, and olt:km its layout when the reader puts km and m first.", + "olt:contours": { + "ft": {"multiplier": 3.28084, "thresholds": {"11": [500, 2500], "12": [200, 1000], "13": [100, 500], "14": [100, 500], "15": [40, 200]}}, + "m": {"multiplier": 1, "thresholds": {"11": [200, 1000], "12": [100, 500], "13": [50, 250], "14": [20, 100], "15": [10, 50]}} + } + }, + "sources": { + "openmaptiles": {"type": "vector", "url": "https://tiles.openfreemap.org/planet"}, + "olt-dem": { + "type": "raster-dem", + "tiles": ["https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"], + "encoding": "terrarium", + "tileSize": 512, + "maxzoom": 12, + "bounds": [-180, 14, -50, 85], + "attribution": "Relief: Terrain Tiles, USGS and others (full credit below the map)" + }, + "olt-contours": {"type": "vector", "tiles": ["contours://{z}/{x}/{y}"], "minzoom": 11, "maxzoom": 15, "bounds": [-180, 14, -50, 85]} + }, + "sprite": "https://tiles.openfreemap.org/sprites/ofm_f384/ofm", + "glyphs": "https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf", + "layers": [ + {"id": "background", "type": "background", + "paint": {"background-color": "#f2efe6"}, + "metadata": {"olt:dark": {"background-color": "#1d241f"}}}, + + {"id": "landcover-ice", "type": "fill", "source": "openmaptiles", "source-layer": "landcover", + "filter": ["==", ["get", "class"], "ice"], + "paint": {"fill-color": "#f6fafc", "fill-outline-color": "#bcd6e6"}, + "metadata": {"olt:dark": {"fill-color": "#2a3338", "fill-outline-color": "#3b4d58"}}}, + {"id": "landcover-rock", "type": "fill", "source": "openmaptiles", "source-layer": "landcover", + "filter": ["==", ["get", "class"], "rock"], + "paint": {"fill-color": "#e3ded4", "fill-antialias": false}, + "metadata": {"olt:dark": {"fill-color": "#2a2b27"}}}, + {"id": "landcover-sand", "type": "fill", "source": "openmaptiles", "source-layer": "landcover", + "filter": ["==", ["get", "class"], "sand"], + "paint": {"fill-color": "#eee3c3", "fill-antialias": false}, + "metadata": {"olt:dark": {"fill-color": "#2d2a20"}}}, + {"id": "landcover-grass", "type": "fill", "source": "openmaptiles", "source-layer": "landcover", + "filter": ["==", ["get", "class"], "grass"], + "paint": {"fill-color": "#e2e8cc", "fill-opacity": 0.8, "fill-antialias": false}, + "metadata": {"olt:dark": {"fill-color": "#202a21"}}}, + {"id": "landcover-wetland", "type": "fill", "source": "openmaptiles", "source-layer": "landcover", + "filter": ["==", ["get", "class"], "wetland"], + "paint": {"fill-color": "#d6e5dc", "fill-antialias": false}, + "metadata": {"olt:dark": {"fill-color": "#1c2b27"}}}, + {"id": "landcover-wood", "type": "fill", "source": "openmaptiles", "source-layer": "landcover", + "filter": ["==", ["get", "class"], "wood"], + "paint": {"fill-color": "#c6dbb0", "fill-antialias": false, + "fill-opacity": ["interpolate", ["linear"], ["zoom"], 3, 0.5, 8, 0.8, 12, 0.9]}, + "metadata": {"olt:dark": {"fill-color": "#22352a"}}}, + {"id": "landuse-built", "type": "fill", "source": "openmaptiles", "source-layer": "landuse", + "filter": ["match", ["get", "class"], ["residential", "suburb", "neighbourhood", "commercial", "industrial", "retail"], true, false], + "paint": {"fill-color": "#e3ddd1", "fill-antialias": false, + "fill-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0.9, 14, 0.6]}, + "metadata": {"olt:dark": {"fill-color": "#272b27"}}}, + {"id": "park-fill", "type": "fill", "source": "openmaptiles", "source-layer": "park", + "filter": ["match", ["geometry-type"], ["Polygon", "MultiPolygon"], true, false], + "paint": {"fill-color": "#4f8a46", "fill-antialias": false, + "fill-opacity": ["interpolate", ["linear"], ["zoom"], 4, 0.1, 10, 0.04]}, + "metadata": {"olt:dark": {"fill-color": "#8fd08a"}}}, + + {"id": "hillshade", "type": "hillshade", "source": "olt-dem", + "paint": {"hillshade-shadow-color": "#4f535c", "hillshade-highlight-color": "#fffdf4", + "hillshade-accent-color": "#5c5a53", "hillshade-illumination-direction": 315, + "hillshade-exaggeration": ["interpolate", ["linear"], ["zoom"], 3, 0.9, 6, 0.7, 9, 0.5, 12, 0.4, 15, 0.3]}, + "metadata": {"olt:dark": {"hillshade-shadow-color": "#000000", "hillshade-highlight-color": "#5d6b60", + "hillshade-accent-color": "#0b0f0d"}}}, + {"id": "contour-minor", "type": "line", "source": "olt-contours", "source-layer": "contours", + "filter": ["==", ["get", "level"], 0], + "paint": {"line-color": "rgba(135, 96, 58, 0.32)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0.5, 15, 0.8]}, + "metadata": {"olt:dark": {"line-color": "rgba(214, 186, 146, 0.24)"}}}, + {"id": "contour-major", "type": "line", "source": "olt-contours", "source-layer": "contours", + "filter": [">", ["get", "level"], 0], + "paint": {"line-color": "rgba(135, 96, 58, 0.55)", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0.8, 15, 1.3]}, + "metadata": {"olt:dark": {"line-color": "rgba(214, 186, 146, 0.42)"}}}, + {"id": "contour-label", "type": "symbol", "source": "olt-contours", "source-layer": "contours", + "filter": [">", ["get", "level"], 0], + "layout": {"symbol-placement": "line", "symbol-spacing": 420, "text-max-angle": 25, + "text-field": ["concat", ["number-format", ["get", "ele"], {"locale": "en-US"}], " ft"], + "text-font": ["Noto Sans Regular"], "text-size": 10, "text-padding": 4}, + "paint": {"text-color": "#86643f", "text-halo-color": "rgba(242, 239, 230, 0.9)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#b89d77", "text-halo-color": "rgba(26, 33, 28, 0.9)"}, + "olt:km": {"text-field": ["concat", ["number-format", ["get", "ele"], {"locale": "en-US"}], " m"]}}}, + + {"id": "water", "type": "fill", "source": "openmaptiles", "source-layer": "water", + "filter": ["!=", ["get", "brunnel"], "tunnel"], + "paint": {"fill-color": "#a6cbe2"}, + "metadata": {"olt:dark": {"fill-color": "#13293a"}}}, + {"id": "waterway-river", "type": "line", "source": "openmaptiles", "source-layer": "waterway", + "filter": ["all", ["==", ["get", "class"], "river"], ["!=", ["get", "brunnel"], "tunnel"]], + "layout": {"line-cap": "round"}, + "paint": {"line-color": "#78acd3", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 8, 0.6, 12, 1.5, 16, 4]}, + "metadata": {"olt:dark": {"line-color": "#2c5877"}}}, + {"id": "waterway-stream", "type": "line", "source": "openmaptiles", "source-layer": "waterway", "minzoom": 11, + "filter": ["all", ["!=", ["get", "class"], "river"], ["!=", ["get", "brunnel"], "tunnel"]], + "layout": {"line-cap": "round"}, + "paint": {"line-color": "#78acd3", "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0.4, 16, 1.5], + "line-opacity": ["case", ["==", ["get", "intermittent"], 1], 0.55, 1]}, + "metadata": {"olt:dark": {"line-color": "#2c5877"}}}, + {"id": "park-outline", "type": "line", "source": "openmaptiles", "source-layer": "park", "minzoom": 7, + "filter": ["match", ["geometry-type"], ["Polygon", "MultiPolygon"], true, false], + "paint": {"line-color": "#6f9a5c", "line-opacity": 0.7, "line-dasharray": [3, 2], + "line-width": ["interpolate", ["linear"], ["zoom"], 7, 0.6, 12, 1.2]}, + "metadata": {"olt:dark": {"line-color": "#5e8a55"}}}, + {"id": "building", "type": "fill", "source": "openmaptiles", "source-layer": "building", "minzoom": 14, + "paint": {"fill-color": "#dcd5c8"}, + "metadata": {"olt:dark": {"fill-color": "#2c312d"}}}, + + {"id": "road-casing", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 10, + "filter": ["match", ["get", "class"], ["motorway", "trunk", "primary", "secondary", "tertiary"], true, false], + "layout": {"line-cap": "round", "line-join": "round"}, + "paint": {"line-color": "#c6baa5", "line-width": ["interpolate", ["exponential", 1.2], ["zoom"], 10, 1.8, 12, 3.6, 16, 11]}, + "metadata": {"olt:dark": {"line-color": "#0f1411"}}}, + {"id": "road-minor-casing", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 12, + "filter": ["match", ["get", "class"], ["minor", "service"], true, false], + "layout": {"line-cap": "round", "line-join": "round"}, + "paint": {"line-color": "#d3cbbc", "line-width": ["interpolate", ["exponential", 1.2], ["zoom"], 12, 1.2, 16, 7]}, + "metadata": {"olt:dark": {"line-color": "#0f1411"}}}, + {"id": "road-track", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 11, + "filter": ["==", ["get", "class"], "track"], + "paint": {"line-color": "#8b7a62", "line-dasharray": [3, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 11, 0.6, 16, 1.6]}, + "metadata": {"olt:dark": {"line-color": "#988b75"}}}, + {"id": "road-path", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 12, + "filter": ["==", ["get", "class"], "path"], + "paint": {"line-color": "#695d4f", "line-dasharray": [2, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 12, 0.6, 16, 1.4]}, + "metadata": {"olt:dark": {"line-color": "#b1a690"}}}, + {"id": "road-minor", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 12, + "filter": ["match", ["get", "class"], ["minor", "service"], true, false], + "layout": {"line-cap": "round", "line-join": "round"}, + "paint": {"line-color": "#ffffff", "line-width": ["interpolate", ["exponential", 1.2], ["zoom"], 12, 0.6, 16, 5]}, + "metadata": {"olt:dark": {"line-color": "#3c433e"}}}, + {"id": "road-secondary", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 9, + "filter": ["match", ["get", "class"], ["secondary", "tertiary"], true, false], + "layout": {"line-cap": "round", "line-join": "round"}, + "paint": {"line-color": "#ffffff", "line-width": ["interpolate", ["exponential", 1.2], ["zoom"], 9, 0.5, 12, 2, 16, 9]}, + "metadata": {"olt:dark": {"line-color": "#4a514b"}}}, + {"id": "road-primary", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 7, + "filter": ["match", ["get", "class"], ["primary", "trunk"], true, false], + "layout": {"line-cap": "round", "line-join": "round"}, + "paint": {"line-color": "#f2dfb0", "line-width": ["interpolate", ["exponential", 1.2], ["zoom"], 7, 0.5, 12, 2.5, 16, 10], + "line-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0.6, 9, 1]}, + "metadata": {"olt:dark": {"line-color": "#5b5747"}}}, + {"id": "road-motorway", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 5, + "filter": ["==", ["get", "class"], "motorway"], + "layout": {"line-cap": "round", "line-join": "round"}, + "paint": {"line-color": "#e8c49a", "line-width": ["interpolate", ["exponential", 1.2], ["zoom"], 5, 0.5, 8, 1.2, 12, 3, 16, 12], + "line-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0.5, 8, 1]}, + "metadata": {"olt:dark": {"line-color": "#6b5c43"}}}, + {"id": "rail", "type": "line", "source": "openmaptiles", "source-layer": "transportation", "minzoom": 9, + "filter": ["==", ["get", "class"], "rail"], + "paint": {"line-color": "#a29e96", "line-width": ["interpolate", ["linear"], ["zoom"], 9, 0.6, 16, 1.4]}, + "metadata": {"olt:dark": {"line-color": "#5b605b"}}}, + {"id": "boundary-state", "type": "line", "source": "openmaptiles", "source-layer": "boundary", "minzoom": 3, + "filter": ["all", ["==", ["get", "admin_level"], 4], ["!=", ["get", "maritime"], 1]], + "paint": {"line-color": "#9a8ea2", "line-dasharray": [4, 2], "line-width": ["interpolate", ["linear"], ["zoom"], 4, 0.6, 10, 1.2]}, + "metadata": {"olt:dark": {"line-color": "#7a7389"}}}, + {"id": "boundary-country", "type": "line", "source": "openmaptiles", "source-layer": "boundary", + "filter": ["all", ["==", ["get", "admin_level"], 2], ["!=", ["get", "maritime"], 1], ["!=", ["get", "disputed"], 1]], + "layout": {"line-join": "round"}, + "paint": {"line-color": "#83788b", "line-width": ["interpolate", ["linear"], ["zoom"], 3, 0.8, 10, 2]}, + "metadata": {"olt:dark": {"line-color": "#8f869c"}}}, + + {"id": "waterway-label", "type": "symbol", "source": "openmaptiles", "source-layer": "waterway", "minzoom": 12, + "filter": ["match", ["geometry-type"], ["LineString", "MultiLineString"], true, false], + "layout": {"symbol-placement": "line", "symbol-spacing": 400, "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], + "text-font": ["Noto Sans Italic"], "text-size": 11, "text-letter-spacing": 0.05}, + "paint": {"text-color": "#36678d", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#86b5d6", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "water-label", "type": "symbol", "source": "openmaptiles", "source-layer": "water_name", + "filter": ["match", ["geometry-type"], ["Point", "MultiPoint"], true, false], + "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["Noto Sans Italic"], + "text-size": ["interpolate", ["linear"], ["zoom"], 5, 10, 12, 12], "text-max-width": 7, "text-letter-spacing": 0.05}, + "paint": {"text-color": "#36678d", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#86b5d6", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "park-label", "type": "symbol", "source": "openmaptiles", "source-layer": "park", "minzoom": 8, + "filter": ["all", ["match", ["geometry-type"], ["Point", "MultiPoint"], true, false], ["has", "name"]], + "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["Noto Sans Italic"], + "text-size": 11, "text-max-width": 8, "text-padding": 8, "symbol-sort-key": ["coalesce", ["get", "rank"], 99]}, + "paint": {"text-color": "#3d6a37", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#94c58d", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "road-label", "type": "symbol", "source": "openmaptiles", "source-layer": "transportation_name", "minzoom": 12, + "filter": ["match", ["get", "class"], ["motorway", "trunk", "primary", "secondary", "tertiary"], true, false], + "layout": {"symbol-placement": "line", "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], + "text-font": ["Noto Sans Regular"], "text-size": 10.5}, + "paint": {"text-color": "#5c574d", "text-halo-color": "rgba(255, 255, 255, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#aaa392", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "path-label", "type": "symbol", "source": "openmaptiles", "source-layer": "transportation_name", "minzoom": 14, + "filter": ["match", ["get", "class"], ["path", "track"], true, false], + "layout": {"symbol-placement": "line", "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], + "text-font": ["Noto Sans Italic"], "text-size": 10}, + "paint": {"text-color": "#695d4f", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#b1a690", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "poi-outdoor", "type": "symbol", "source": "openmaptiles", "source-layer": "poi", "minzoom": 13, + "filter": ["match", ["get", "subclass"], ["camp_site", "alpine_hut", "wilderness_hut", "shelter"], true, false], + "layout": {"icon-image": ["match", ["get", "subclass"], "camp_site", "campsite_11", "shelter", "shelter_11", "lodging_11"], + "text-field": ["step", ["zoom"], "", 14, ["coalesce", ["get", "name_en"], ["get", "name"], ""]], + "text-font": ["Noto Sans Regular"], "text-size": 10, "text-anchor": "top", "text-offset": [0, 0.8], + "text-max-width": 8, "text-optional": true}, + "paint": {"text-color": "#5a4a3a", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#cdc2ab", "text-halo-color": "rgba(26, 33, 28, 0.85)", "icon-opacity": 0.85}}}, + {"id": "peak", "type": "symbol", "source": "openmaptiles", "source-layer": "mountain_peak", "minzoom": 9, + "filter": ["all", ["match", ["get", "class"], ["peak", "volcano"], true, false], ["has", "name"]], + "layout": {"text-field": ["format", "▲", {"font-scale": 0.85}, "\n", {}, ["coalesce", ["get", "name_en"], ["get", "name"]], {}, + ["case", ["has", "ele_ft"], ["concat", "\n", ["number-format", ["get", "ele_ft"], {"locale": "en-US"}], " ft"], ""], {"font-scale": 0.85}], + "text-font": ["Noto Sans Regular"], "text-size": 11, "text-anchor": "top", "text-offset": [0, -0.55], + "text-line-height": 1.15, "text-max-width": 8, "text-padding": 6, + "symbol-sort-key": ["-", 0, ["coalesce", ["get", "ele"], 0]]}, + "paint": {"text-color": "#4a3a29", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#ddd0b5", "text-halo-color": "rgba(26, 33, 28, 0.85)"}, + "olt:km": {"text-field": ["format", "▲", {"font-scale": 0.85}, "\n", {}, ["coalesce", ["get", "name_en"], ["get", "name"]], {}, + ["case", ["has", "ele"], ["concat", "\n", ["number-format", ["get", "ele"], {"locale": "en-US"}], " m"], ""], {"font-scale": 0.85}]}}}, + {"id": "place-hamlet", "type": "symbol", "source": "openmaptiles", "source-layer": "place", "minzoom": 12, + "filter": ["match", ["get", "class"], ["hamlet", "locality", "isolated_dwelling"], true, false], + "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["Noto Sans Regular"], + "text-size": 10, "text-max-width": 8}, + "paint": {"text-color": "#4f5650", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#b4ad9b", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "place-village", "type": "symbol", "source": "openmaptiles", "source-layer": "place", "minzoom": 10, + "filter": ["==", ["get", "class"], "village"], + "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["Noto Sans Regular"], + "text-size": ["interpolate", ["linear"], ["zoom"], 10, 10.5, 14, 12], "text-max-width": 8}, + "paint": {"text-color": "#343a35", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#cfc8b6", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "place-town", "type": "symbol", "source": "openmaptiles", "source-layer": "place", "minzoom": 7, + "filter": ["==", ["get", "class"], "town"], + "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["Noto Sans Regular"], + "text-size": ["interpolate", ["linear"], ["zoom"], 7, 10.5, 12, 13], "text-max-width": 8}, + "paint": {"text-color": "#2c322d", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#ddd6c4", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "place-city", "type": "symbol", "source": "openmaptiles", "source-layer": "place", "minzoom": 4, + "filter": ["==", ["get", "class"], "city"], + "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["Noto Sans Regular"], + "text-size": ["interpolate", ["linear"], ["zoom"], 4, 11, 10, 15], "text-max-width": 8, + "symbol-sort-key": ["coalesce", ["get", "rank"], 99]}, + "paint": {"text-color": "#232824", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.4}, + "metadata": {"olt:dark": {"text-color": "#e6dfcd", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "place-state", "type": "symbol", "source": "openmaptiles", "source-layer": "place", "minzoom": 4, "maxzoom": 8, + "filter": ["==", ["get", "class"], "state"], + "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["Noto Sans Italic"], + "text-size": ["interpolate", ["linear"], ["zoom"], 4, 10, 8, 12], "text-transform": "uppercase", + "text-letter-spacing": 0.15, "text-max-width": 9}, + "paint": {"text-color": "#776f7e", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#9c94a8", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}}, + {"id": "place-country", "type": "symbol", "source": "openmaptiles", "source-layer": "place", "maxzoom": 7, + "filter": ["==", ["get", "class"], "country"], + "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["Noto Sans Bold"], + "text-size": ["interpolate", ["linear"], ["zoom"], 2, 10, 6, 13], "text-max-width": 7}, + "paint": {"text-color": "#5b5462", "text-halo-color": "rgba(242, 239, 230, 0.85)", "text-halo-width": 1.2}, + "metadata": {"olt:dark": {"text-color": "#b0a8bb", "text-halo-color": "rgba(26, 33, 28, 0.85)"}}} + ] +} diff --git a/web/assets/prefs.js b/web/assets/prefs.js index fff99cc..d24adef 100644 --- a/web/assets/prefs.js +++ b/web/assets/prefs.js @@ -1,5 +1,6 @@ /* Runs in , before first paint: marks that JavaScript runs, and applies the - reader's saved theme and length order. Saved by app.js (footer switches). */ + reader's saved theme, length order and base map. Saved by app.js (the footer + switches, and the Outdoor / Plain switch on a trail map). */ (function () { 'use strict'; var root = document.documentElement; @@ -7,7 +8,9 @@ try { var theme = localStorage.getItem('lh-theme'); var units = localStorage.getItem('lh-units'); + var basemap = localStorage.getItem('lh-basemap'); if (theme === 'light' || theme === 'dark') root.dataset.theme = theme; if (units === 'km') root.dataset.units = 'km'; /* anything else, an old 'mi' included, is miles */ + if (basemap === 'plain') root.dataset.basemap = 'plain'; /* anything else is the outdoor map */ } catch (e) { /* storage blocked: defaults apply */ } })(); diff --git a/web/assets/style.css b/web/assets/style.css index f3fc56d..c60f8de 100644 --- a/web/assets/style.css +++ b/web/assets/style.css @@ -704,6 +704,22 @@ body:has(.hero--home) .site-header .wordmark { visibility: hidden; } :root:not([data-theme="light"]) .maplibregl-ctrl-icon, :root:not([data-theme="light"]) .maplibregl-ctrl-attrib-button { filter: invert(1); } } +/* The Outdoor / Plain switch of a trail map (app.js basemapControl): two toggle + buttons side by side, top left, the pressed one in ink like a .seg choice. */ +.maplibregl-ctrl-group.basemap-switch { display: flex; } +.maplibregl-ctrl-group.basemap-switch button { + inline-size: auto; block-size: auto; width: auto; height: auto; + min-block-size: 29px; + padding: 0 var(--space-2); + color: var(--ink-2); + font: 500 0.75rem/1 var(--font-sans); +} +.maplibregl-ctrl-group.basemap-switch button + button { border-block-start: 0; border-inline-start: 1px solid var(--rule); } +.maplibregl-ctrl-group.basemap-switch button[aria-pressed="true"]:not(:disabled) { background: var(--ink); color: var(--paper); font-weight: 600; } +.maplibregl-ctrl-group.basemap-switch button[aria-pressed="true"]:focus-visible { outline-color: var(--paper); } +@media (pointer: coarse) { + .maplibregl-ctrl-group.basemap-switch button { min-block-size: 2.75rem; padding: 0 var(--space-3); } +} .maplibregl-ctrl-scale { background: color-mix(in srgb, var(--surface) 88%, transparent) !important; border-color: var(--ink) !important; diff --git a/web/assets/vendor/README.md b/web/assets/vendor/README.md index 57a1904..35aee97 100644 --- a/web/assets/vendor/README.md +++ b/web/assets/vendor/README.md @@ -1,7 +1,8 @@ # Third-party assets Served from `/assets/`, so pages make no requests to CDNs or font services at -runtime. Map tiles, glyphs and sprites still come from OpenFreeMap. +runtime. Map tiles, glyphs and sprites still come from OpenFreeMap, and the +trail maps' elevation tiles from Terrain Tiles on AWS. ## MapLibre GL JS @@ -25,6 +26,44 @@ To upgrade: download `dist/maplibre-gl.js`, `dist/maplibre-gl.css` and `LICENSE.txt` of the new version into `maplibre-gl/`, update this file, and check that the trail maps still draw. +## maplibre-contour + +| File | Package | Version | Licence | +| --- | --- | --- | --- | +| `maplibre-contour/maplibre-contour.js` | maplibre-contour | 0.1.1 | BSD-3-Clause (with code from d3-contour, ISC, and vt-pbf, MIT), `maplibre-contour/LICENSE.txt` | + +Draws the contour lines of the trail pages' outdoor map in the browser, from +the same elevation tiles as the relief. `maplibre-contour.js` is the package's +`dist/index.min.js` and `LICENSE.txt` its `LICENSE`, unchanged, from the npm +tarball `https://registry.npmjs.org/maplibre-contour/-/maplibre-contour-0.1.1.tgz` +(SHA-1 `d8aa3e3b62c8d097fc4eacb3d849635a0b662ede`, as the registry lists it), +downloaded 2026-11-15; unpkg serves the same bytes. SHA-256: + +```text +055e45d0a76aaeaaf5a96765b8ce524abba3272456be75e715081e235ebd1262 maplibre-contour.js +b4a3261f4af65db24e6a2ca23093ac25619e6fe0b5ca5ec75fb09a49817b5c8d LICENSE.txt +``` + +It defines `window.mlcontour`. Only trail pages load it (deferred, after +MapLibre; `olt/layout.py` `outdoor=True`), and `app.js` draws the map without +contours when it is missing. It runs its work in a worker made from a `blob:` +URL (`worker-src blob:`) and fetches the elevation tiles there with `fetch()` +(`connect-src` names the tiles' path). No `eval`, no source map. + +To upgrade: put `dist/index.min.js` of the new version here as +`maplibre-contour.js`, with its `LICENSE`, update this file, and check the +contours and the relief on a trail page in Firefox and in Chromium. + +## Outdoor map style (`../map/`) + +`outdoor.json` is this site's own style for the trail pages' outdoor map, +derived from OpenFreeMap's Liberty style (MIT), a fork of OSM Liberty and OSM +Bright (BSD-3-Clause code, CC BY 4.0 design). `LICENSE.txt` beside it keeps +their notices; the design credit, "© OpenMapTiles", is in the corner of every +map. The style keeps OpenFreeMap's tiles, glyphs and sprites. Its elevation +source is Terrain Tiles on AWS, the data `tools/elevation.py` uses, credited +under every trail map (`olt/common.py` `TRAIL_MAP_CREDIT`). + ## Web fonts (`../fonts/`) Latin subset only, as served by Google Fonts on 2026-11-10. Characters outside diff --git a/web/assets/vendor/maplibre-contour/LICENSE.txt b/web/assets/vendor/maplibre-contour/LICENSE.txt new file mode 100644 index 0000000..014eea4 --- /dev/null +++ b/web/assets/vendor/maplibre-contour/LICENSE.txt @@ -0,0 +1,72 @@ +BSD 3-Clause License + +Copyright (c) 2023, Michael Barry and maplibre-contour contributors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--- + +Contains code from d3-contour https://github.com/d3/d3-contour + +Copyright 2012-2023 Mike Bostock + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +--- + +Contains code from vt-pbf https://github.com/mapbox/vt-pbf + +The MIT License (MIT) + +Copyright (c) 2015 Anand Thakker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/web/assets/vendor/maplibre-contour/maplibre-contour.js b/web/assets/vendor/maplibre-contour/maplibre-contour.js new file mode 100644 index 0000000..948099c --- /dev/null +++ b/web/assets/vendor/maplibre-contour/maplibre-contour.js @@ -0,0 +1,15 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).mlcontour=e()}(this,(function(){"use strict";var t,e,i;function r(r,s){if(t)if(e){var n="var sharedChunk = {}; ("+t+")(sharedChunk); ("+e+")(sharedChunk);",o={};t(o),i=s(o),"undefined"!=typeof window&&(i.workerUrl=window.URL.createObjectURL(new Blob([n],{type:"text/javascript"})))}else e=s;else t=s}return r(0,(function(t){class e{constructor(t,e){this.start=t,this.end=e,this.points=[],this.append=this.append.bind(this),this.prepend=this.prepend.bind(this)}append(t,e){this.points.push(Math.round(t),Math.round(e))}prepend(t,e){this.points.splice(0,0,Math.round(t),Math.round(e))}lineString(){return this.toArray()}isEmpty(){return this.points.length<2}appendFragment(t){this.points.push(...t.points),this.end=t.end}toArray(){return this.points}}const i=[[],[[[1,2],[0,1]]],[[[2,1],[1,2]]],[[[2,1],[0,1]]],[[[1,0],[2,1]]],[[[1,2],[0,1]],[[1,0],[2,1]]],[[[1,0],[1,2]]],[[[1,0],[0,1]]],[[[0,1],[1,0]]],[[[1,2],[1,0]]],[[[0,1],[1,0]],[[2,1],[1,2]]],[[[2,1],[1,0]]],[[[0,1],[2,1]]],[[[1,2],[2,1]]],[[[0,1],[1,2]]],[]];function r(t,e,i,r){return(e=2*e+r[0])+(i=2*i+r[1])*(t+1)*2}function s(t,e,i){return(e-t)/(i-t)}function n(t,n,o=4096,a=1){if(!t)return{};const h=o/(n.width-1);let l,c,d,u,f,p;const w={},g=new Map,m=new Map;function b(t,e,i){0===t[0]?i(h*(p-1),h*(f-s(d,e,l))):2===t[0]?i(h*p,h*(f-s(u,e,c))):0===t[1]?i(h*(p-s(c,e,l)),h*(f-1)):i(h*(p-s(u,e,d)),h*f)}for(f=1-a;fs,o=c>s,a=d>s,h=u>s;for(const l of i[(t?8:0)|(o?4:0)|(h?2:0)|(a?1:0)]){let t=g.get(s);t||g.set(s,t=new Map);let i=m.get(s);i||m.set(s,i=new Map);const o=l[0],a=l[1],h=r(n.width,p,f,o),c=r(n.width,p,f,a);let d,u;if(d=i.get(h))if(i.delete(h),u=t.get(c))if(t.delete(c),d===u){if(b(a,s,d.append),!d.isEmpty()){let t=w[s];t||(w[s]=t=[]),t.push(d.lineString())}}else d.appendFragment(u),i.set(d.end=u.end,d);else b(a,s,d.append),i.set(d.end=c,d);else if(d=t.get(c))t.delete(c),b(o,s,d.prepend),t.set(d.start=h,d);else{const r=new e(h,c);b(o,s,r.append),b(a,s,r.append),t.set(h,r),i.set(c,r)}}}}}for(const[t,e]of g.entries()){let i=null;for(const r of e.values())r.isEmpty()||(null==i&&(i=w[t]||(w[t]=[])),i.push(r.lineString()))}return w} +/*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */function o(t,e){var i={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(i[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(t);ste?1:0)),e}function l(t){return h(t).map((([t,e])=>[t,..."number"==typeof e?[e]:e].join("*"))).join("~")}function c(t){return h(t).map((([t,e])=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`)).join(",")}function d(t){const e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(new Uint8Array(t)),e}let u=null;function f(){return null==u&&(u="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),u||!1}let p=null;function w(t,e,i){let r=()=>{};const s=setTimeout((()=>{r(new Error("timed out")),null==i||i.abort()}),t);g(i,(()=>{r(new Error("aborted")),clearTimeout(s)}));const n=new Promise(((t,e)=>{r=e}));return Promise.race([n,e.finally((()=>clearTimeout(s)))])}function g(t,e){e&&(null==t||t.signal.addEventListener("abort",e))}function m(t){var e;return Boolean(null===(e=null==t?void 0:t.signal)||void 0===e?void 0:e.aborted)}let b,y,v,x,P=0;class F{constructor(t=100){this.size=()=>this.items.size,this.get=(t,e,i)=>{let r=this.items.get(t);if(r)r.lastUsed=++P,r.waiting++;else{const i=new AbortController,s=e(t,i);r={abortController:i,item:s,lastUsed:++P,waiting:1},this.items.set(t,r),this.prune()}const s=this.items,n=r.item.then((t=>t),(e=>(s.delete(t),Promise.reject(e))));let o=!1;return g(i,(()=>{var e;r&&r.abortController&&!o&&(o=!0,--r.waiting<=0&&(null===(e=r.abortController)||void 0===e||e.abort(),s.delete(t)))})),n},this.clear=()=>this.items.clear(),this.maxSize=t,this.items=new Map}prune(){if(this.items.size>this.maxSize){let t,e=1/0;this.items.forEach(((i,r)=>{i.lastUsedr.src=""));return M(yield new Promise(((e,s)=>{r.onload=()=>{m(i)||e(r),URL.revokeObjectURL(r.src),r.onload=null},r.onerror=()=>s(new Error("Could not load image.")),r.src=t.size?URL.createObjectURL(t):""})),e,v,x)}))};function M(t,e,i,r){if(i.width=t.width,i.height=t.height,!r)throw new Error("failed to get context");r.drawImage(t,0,0,t.width,t.height);const s=r.getImageData(0,0,t.width,t.height).data;return S(t.width,t.height,e,s)}function S(t,e,i,r){const s="mapbox"===i?(t,e,i)=>.1*(256*t*256+256*e+i)-1e4:(t,e,i)=>256*t+e+i/256-32768,n=new Float32Array(t*e);for(let t=0;t{if(0===t)return this;const r=1<this.get(t+s,e+n)))},this.subsamplePixelCenters=t=>{const e=(t,e,i)=>isNaN(t)?e:isNaN(e)?t:t+(e-t)*i;if(t<=1)return this;const i=.5-1/(2*t);return new T(this.width*t,this.height*t,((r,s)=>{const n=r/t-i,o=s/t-i,a=Math.floor(n),h=Math.floor(o),l=this.get(a,h),c=this.get(a+1,h),d=this.get(a,h+1),u=this.get(a+1,h+1),f=n-a,p=o-h,w=e(l,c,f),g=e(d,u,f);return e(w,g,p)}))},this.averagePixelCentersToGrid=(t=1)=>new T(this.width+1,this.height+1,((e,i)=>{let r=0,s=0,n=0;for(let o=e-t;o1===t?this:new T(this.width,this.height,((e,i)=>this.get(e,i)*t)),this.materialize=(t=2)=>{const e=this.width+2*t,i=new Float32Array(e*(this.height+2*t));let r=0;for(let e=-t;ei[(s+t)*e+r+t]))},this.get=i,this.width=t,this.height=e}static fromRawDem(t){return new T(t.width,t.height,((e,i)=>{const r=t.data[i*t.width+e];return s=r,!isNaN(s)&&s>=-12e3&&s<=9e3?r:NaN;var s}))}static combineNeighbors(t){if(9!==t.length)throw new Error("Must include a tile plus 8 neighbors");const e=t[4];if(!e)return;const i=e.width,r=e.height;return new T(i,r,((e,s)=>{let n=0;s<0?s+=r:s>3,s=this.pos;this.type=7&i,t(r,e,this),this.pos===s&&this.skip(i)}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*N;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*N;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let i,r;return r=e[this.pos++],i=127&r,r<128?i:(r=e[this.pos++],i|=(127&r)<<7,r<128?i:(r=e[this.pos++],i|=(127&r)<<14,r<128?i:(r=e[this.pos++],i|=(127&r)<<21,r<128?i:(r=e[this.pos],i|=(15&r)<<28,function(t,e,i){const r=i.buf;let s,n;if(n=r[i.pos++],s=(112&n)>>4,n<128)return E(t,s,e);if(n=r[i.pos++],s|=(127&n)<<3,n<128)return E(t,s,e);if(n=r[i.pos++],s|=(127&n)<<10,n<128)return E(t,s,e);if(n=r[i.pos++],s|=(127&n)<<17,n<128)return E(t,s,e);if(n=r[i.pos++],s|=(127&n)<<24,n<128)return E(t,s,e);if(n=r[i.pos++],s|=(1&n)<<31,n<128)return E(t,s,e);throw new Error("Expected varint not more than 10 bytes")}(i,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&O?O.decode(this.buf.subarray(e,t)):function(t,e,i){let r="",s=e;for(;s239?4:e>223?3:e>191?2:1;if(s+l>i)break;1===l?e<128&&(h=e):2===l?(n=t[s+1],128==(192&n)&&(h=(31&e)<<6|63&n,h<=127&&(h=null))):3===l?(n=t[s+1],o=t[s+2],128==(192&n)&&128==(192&o)&&(h=(15&e)<<12|(63&n)<<6|63&o,(h<=2047||h>=55296&&h<=57343)&&(h=null))):4===l&&(n=t[s+1],o=t[s+2],a=t[s+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&(h=(15&e)<<18|(63&n)<<12|(63&o)<<6|63&a,(h<=65535||h>=1114112)&&(h=null))),null===h?(h=65533,l=1):h>65535&&(h-=65536,r+=String.fromCharCode(h>>>10&1023|55296),h=56320|1023&h),r+=String.fromCharCode(h),s+=l}return r}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const i=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else{if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8}}writeTag(t,e){this.writeVarint(t<<3|e)}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let i,r;t>=0?(i=t%4294967296|0,r=t/4294967296|0):(i=~(-t%4294967296),r=~(-t/4294967296),4294967295^i?i=i+1|0:(i=0,r=r+1|0));if(t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,i){i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos]=127&t}(i,0,e),function(t,e){const i=(7&t)<<4;if(e.buf[e.pos++]|=i|((t>>>=3)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;e.buf[e.pos++]=127&t}(r,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))}writeSVarint(t){this.writeVarint(t<0?2*-t-1:2*t)}writeBoolean(t){this.writeVarint(+t)}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,i){for(let r,s,n=0;n55295&&r<57344){if(!s){r>56319||n+1===e.length?(t[i++]=239,t[i++]=191,t[i++]=189):s=r;continue}if(r<56320){t[i++]=239,t[i++]=191,t[i++]=189,s=r;continue}r=s-55296<<10|r-56320|65536,s=null}else s&&(t[i++]=239,t[i++]=191,t[i++]=189,s=null);r<128?t[i++]=r:(r<2048?t[i++]=r>>6|192:(r<65536?t[i++]=r>>12|224:(t[i++]=r>>18|240,t[i++]=r>>12&63|128),t[i++]=r>>6&63|128),t[i++]=63&r|128)}return i}(this.buf,t,this.pos);const i=this.pos-e;i>=128&&U(e,i,this),this.pos=e-1,this.writeVarint(i),this.pos+=i}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let i=0;i=128&&U(i,r,this),this.pos=i-1,this.writeVarint(r),this.pos+=r}writeMessage(t,e,i){this.writeTag(t,2),this.writeRawMessage(e,i)}writePackedVarint(t,e){e.length&&this.writeMessage(t,B,e)}writePackedSVarint(t,e){e.length&&this.writeMessage(t,A,e)}writePackedBoolean(t,e){e.length&&this.writeMessage(t,z,e)}writePackedFloat(t,e){e.length&&this.writeMessage(t,D,e)}writePackedDouble(t,e){e.length&&this.writeMessage(t,j,e)}writePackedFixed32(t,e){e.length&&this.writeMessage(t,R,e)}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,$,e)}writePackedFixed64(t,e){e.length&&this.writeMessage(t,L,e)}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,G,e)}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e)}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e)}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e)}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e)}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e)}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e)}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e)}writeStringField(t,e){this.writeTag(t,2),this.writeString(e)}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e)}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e)}writeBooleanField(t,e){this.writeVarintField(t,+e)}}function E(t,e,i){return i?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function U(t,e,i){const r=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));i.realloc(r);for(let e=i.pos-1;e>=t;e--)i.buf[e+r]=i.buf[e]}function B(t,e){for(let i=0;i>31}function J(t,e){if(!e)throw new Error;const i=t.geometry,r=t.type;let s=0,n=0;for(const t of i){let i=1;r===W.POINT&&(i=t.length/2),e.writeVarint(_(1,i));const o=t.length/2,a=r===W.POLYGON?o-1:o;for(let i=0;i{this.markFinish();const e=t=>{const e=this.marks[t]||[],i=Math.max(...e.map((t=>Math.max(...t)))),r=Math.min(...e.map((t=>Math.min(...t))));return Number.isFinite(i)?i-r:void 0},i=e("main")||0,r=e("fetch"),s=e("decode"),n=e("isoline");return{url:t,tilesUsed:this.tilesFetched,origin:this.timeOrigin,marks:this.marks,resources:[...this.resources,...it(this.fetched.map(tt))],duration:i,fetch:r,decode:s,process:n,wait:i-(r||0)-(s||0)-(n||0)}},this.error=t=>Object.assign(Object.assign({},this.finish(t)),{error:!0}),this.marker=t=>{var e;this.marks[t]||(this.marks[t]=[]);const i=[et()];return null===(e=this.marks[t])||void 0===e||e.push(i),()=>i.push(et())},this.useTile=t=>{this.urls.indexOf(t)<0&&(this.urls.push(t),this.tilesFetched++)},this.fetchTile=t=>{this.fetched.indexOf(t)<0&&this.fetched.push(t)},this.addAll=t=>{var e;this.tilesFetched+=t.tilesUsed;const i=t.origin-this.timeOrigin;for(const r in t.marks){const s=r;(this.marks[s]||(this.marks[s]=[])).push(...(null===(e=t.marks[s])||void 0===e?void 0:e.map((t=>t.map((t=>t+i)))))||[])}this.resources.push(...t.resources.map((t=>function(t,e){const i={};for(const r in t)0!==t[r]&&st.test(r)?i[r]=Number(t[r])+e:i[r]=t[r];return i}(t,i))))},this.markFinish=this.marker(t)}}const st=/(Start$|End$|^start|^end)/;const nt=(t,e)=>a(void 0,void 0,void 0,(function*(){const i={signal:e.signal},r=yield fetch(t,i);if(!r.ok)throw new Error(`Bad response: ${r.status} for ${t}`);return{data:yield r.blob(),expires:r.headers.get("expires")||void 0,cacheControl:r.headers.get("cache-control")||void 0}}));let ot=0;t.A=class{constructor(t,e,i=2e4){this.callbacks={},this.cancels={},this.dest=t,this.timeoutMs=i,this.dest.onmessage=t=>a(this,[t],void 0,(function*({data:t}){const i=t;if("cancel"===i.type){const t=this.cancels[i.id];delete this.cancels[i.id],null==t||t.abort()}else if("response"===i.type){const t=this.callbacks[i.id];delete this.callbacks[i.id],t&&t(i.error?new Error(i.error):void 0,i.response,i.timings)}else if("request"===i.type){const t=new rt("worker"),r=e[i.name],s=new AbortController,n=r.apply(r,[...i.args,s,t]),o=`${i.name}_${i.id}`;if(i.id&&n){this.cancels[i.id]=s;try{const e=yield n,r=null==e?void 0:e.transferrables;this.postMessage({id:i.id,type:"response",response:e,timings:t.finish(o)},r)}catch(e){this.postMessage({id:i.id,type:"response",error:(null==e?void 0:e.toString())||"error",timings:t.finish(o)})}delete this.cancels[i.id]}}}))}postMessage(t,e){this.dest.postMessage(t,e||[])}send(t,e,i,r,...s){const n=++ot,o=new Promise(((i,o)=>{this.postMessage({id:n,type:"request",name:t,args:s},e),this.callbacks[n]=(t,e,s)=>{null==r||r.addAll(s),t?o(t):i(e)}}));return g(i,(()=>{delete this.callbacks[n],this.postMessage({id:n,type:"cancel"})})),w(this.timeoutMs,o,i)}},t.H=T,t.L=class{constructor(t){this.loaded=Promise.resolve(),this.fetchAndParseTile=(t,e,i,r,s)=>{const n=this,o=this.demUrlPattern.replace("{z}",t.toString()).replace("{x}",e.toString()).replace("{y}",i.toString());return null==s||s.useTile(o),this.parsedCache.get(o,((r,o)=>a(this,void 0,void 0,(function*(){const r=yield n.fetchTile(t,e,i,o,s);if(m(o))throw new Error("canceled");const a=n.decodeImage(r.data,n.encoding,o),h=null==s?void 0:s.marker("decode"),l=yield a;return null==h||h(),l}))),r)},this.tileCache=new F(t.cacheSize),this.parsedCache=new F(t.cacheSize),this.contourCache=new F(t.cacheSize),this.timeoutMs=t.timeoutMs,this.demUrlPattern=t.demUrlPattern,this.encoding=t.encoding,this.maxzoom=t.maxzoom,this.decodeImage=t.decodeImage||V,this.getTile=t.getTile||nt}fetchTile(t,e,i,r,s){const n=this.demUrlPattern.replace("{z}",t.toString()).replace("{x}",e.toString()).replace("{y}",i.toString());return null==s||s.useTile(n),this.tileCache.get(n,((t,e)=>{null==s||s.fetchTile(n);const i=null==s?void 0:s.marker("fetch");return w(this.timeoutMs,this.getTile(n,e).finally((()=>null==i?void 0:i())),e)}),r)}fetchDem(t,e,i,r,s,n){return a(this,void 0,void 0,(function*(){const o=Math.max(0,Math.min(t-(r.overzoom||0),this.maxzoom)),a=t-o,h=1<a(this,void 0,void 0,(function*(){const s=1<=s?void 0:this.fetchDem(t,(i+s)%s,n,r,c,o));const d=yield Promise.all(a);let y=T.combineNeighbors(d);if(!y||m(c))return{arrayBuffer:(new Uint8Array).buffer};const v=null==o?void 0:o.marker("isoline");if(y.width>=b)y=y.materialize(2);else for(;y.width{const i=Number(t);return{type:W.LINESTRING,geometry:e,properties:{[w]:i,[g]:Math.max(...h.map(((t,e)=>i%t==0?e:0)))}}}))}}});return null==v||v(),{arrayBuffer:P.slice().buffer}}))),s);return v.then((({arrayBuffer:t})=>({arrayBuffer:d(t)})))}},t.T=rt,t._=a,t.a=function(t){const[,e,i,r]=/\/\/(\d+)\/(\d+)\/(\d+)/.exec(t)||[];return[Number(e),Number(i),Number(r)]},t.b=function(t){return Object.fromEntries(t.replace(/^.*\?/,"").split("&").map((t=>{const e=t.split("=").map(decodeURIComponent),i=e[0];let r=e[1];switch(i){case"thresholds":s=r,r=Object.fromEntries(s.split("~").map((t=>t.split("*").map(Number))).map((([t,...e])=>[t,e])));break;case"extent":case"multiplier":case"overzoom":case"buffer":r=Number(r)}var s;return[i,r]})))},t.c=S,t.d=V,t.e=function(t){var{thresholds:e}=t,i=o(t,["thresholds"]);return h(Object.assign({thresholds:l(e)},i)).map((([t,e])=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`)).join("&")},t.f=n,t.g=function(t,e){const{thresholds:i}=t,r=o(t,["thresholds"]);let s=[],n=-1/0;return Object.entries(i).forEach((([t,i])=>{const r=Number(t);r<=e&&r>n&&(n=r,s="number"==typeof i?[i]:i)})),Object.assign({levels:s},r)},t.h=function(t){return t.then((({arrayBuffer:t})=>({arrayBuffer:t,transferrables:[t]})))},t.p=function(t,e){return t.then((t=>{var{data:i}=t,r=o(t,["data"]);let s=i;return e&&(s=new Float32Array(i.length),s.set(i)),Object.assign(Object.assign({},r),{data:s,transferrables:[s.buffer]})}))}})),r(0,(function(t){const e=t=>Promise.reject(new Error(`No manager registered for ${t}`));const i="undefined"!=typeof self?self:"undefined"!=typeof window?window:global;i.actor=new t.A(i,new class{constructor(){this.managers={},this.init=(e,i)=>(this.managers[e.managerId]=new t.L(e),Promise.resolve()),this.fetchTile=(t,i,r,s,n,o)=>{var a;return(null===(a=this.managers[t])||void 0===a?void 0:a.fetchTile(i,r,s,n,o))||e(t)},this.fetchAndParseTile=(i,r,s,n,o,a)=>{var h;return t.p((null===(h=this.managers[i])||void 0===h?void 0:h.fetchAndParseTile(r,s,n,o,a))||e(i),!0)},this.fetchContourTile=(i,r,s,n,o,a,h)=>{var l;return t.h((null===(l=this.managers[i])||void 0===l?void 0:l.fetchContourTile(r,s,n,o,a,h))||e(i))}}})})),r(0,(function(t){const e={workerUrl:""};let i,r=0;class s{constructor(){this.decodeImage=(e,i,r)=>t.p(t.d(e,i,r),!1)}}class n{constructor(n){this.fetchTile=(t,e,i,r,s)=>this.actor.send("fetchTile",[],r,s,this.managerId,t,e,i),this.fetchAndParseTile=(t,e,i,r,s)=>this.actor.send("fetchAndParseTile",[],r,s,this.managerId,t,e,i),this.fetchContourTile=(t,e,i,r,s,n)=>this.actor.send("fetchContourTile",[],s,n,this.managerId,t,e,i,r);const o=this.managerId=++r;this.actor=n.actor||function(){if(!i){const r=new Worker(e.workerUrl),n=new s;i=new t.A(r,n)}return i}(),this.loaded=this.actor.send("init",[],new AbortController,void 0,Object.assign(Object.assign({},n),{managerId:o}))}}Blob.prototype.arrayBuffer||(Blob.prototype.arrayBuffer=function(){return new Promise(((t,e)=>{const i=new FileReader;i.onload=e=>{var i;return t(null===(i=e.target)||void 0===i?void 0:i.result)},i.onerror=e,i.readAsArrayBuffer(this)}))});const o=t=>(e,i)=>{if(i instanceof AbortController)return t(e,i);{const r=new AbortController;return t(e,r).then((t=>i(void 0,t.data,t.cacheControl,t.expires)),(t=>i(t))).catch((t=>i(t))),{cancel:()=>r.abort()}}},a=new Set;const h={generateIsolines:t.f,DemSource:class{constructor({url:e,cacheSize:i=100,id:r="dem",encoding:s="terrarium",maxzoom:h=12,worker:l=!0,timeoutMs:c=1e4,actor:d}){this.timingCallbacks=[],this.onTiming=t=>{this.timingCallbacks.push(t)},this.setupMaplibre=t=>{t.addProtocol(this.sharedDemProtocolId,this.sharedDemProtocol),t.addProtocol(this.contourProtocolId,this.contourProtocol)},this.sharedDemProtocolV4=(e,i)=>t._(this,void 0,void 0,(function*(){const[r,s,n]=t.a(e.url),o=new t.T("main");let a;try{const t=yield this.manager.fetchTile(r,s,n,i,o);a=o.finish(e.url);return{data:yield t.data.arrayBuffer(),cacheControl:t.cacheControl,expires:t.expires}}catch(t){throw a=o.error(e.url),t}finally{this.timingCallbacks.forEach((t=>t(a)))}})),this.contourProtocolV4=(e,i)=>t._(this,void 0,void 0,(function*(){const r=new t.T("main");let s;try{const[n,o,a]=t.a(e.url),h=t.b(e.url),l=yield this.manager.fetchContourTile(n,o,a,t.g(h,n),i,r);return s=r.finish(e.url),{data:l.arrayBuffer}}catch(t){throw s=r.error(e.url),t}finally{this.timingCallbacks.forEach((t=>t(s)))}})),this.contourProtocol=o(this.contourProtocolV4),this.sharedDemProtocol=o(this.sharedDemProtocolV4),this.contourProtocolUrl=e=>`${this.contourProtocolUrlBase}?${t.e(e)}`;let u=r,f=1;for(;a.has(u);)u=r+f++;a.add(u),this.sharedDemProtocolId=`${u}-shared`,this.contourProtocolId=`${u}-contour`,this.sharedDemProtocolUrl=`${this.sharedDemProtocolId}://{z}/{x}/{y}`,this.contourProtocolUrlBase=`${this.contourProtocolId}://{z}/{x}/{y}`;const p=l?n:t.L;this.manager=new p({demUrlPattern:e,cacheSize:i,encoding:s,maxzoom:h,timeoutMs:c,actor:d})}getDemTile(t,e,i,r){return this.manager.fetchAndParseTile(t,e,i,r||new AbortController)}},HeightTile:t.H,LocalDemManager:t.L,decodeParsedImage:t.c,set workerUrl(t){e.workerUrl=t},get workerUrl(){return e.workerUrl}};return h})),i})); diff --git a/web/olt/common.py b/web/olt/common.py index 0810f97..59d58b9 100644 --- a/web/olt/common.py +++ b/web/olt/common.py @@ -183,6 +183,30 @@ def plate(rec, *, size="", link=False, eager=False, alt=None): return Markup(f'') +# Map credits. The base map is OpenFreeMap on every map. The trail maps add +# relief and contours drawn from the Terrain Tiles elevation data: their credit +# is the one tools/elevation.py gives (ATTRIBUTION; test_pages checks the two +# agree), plus Mexico, which the maps near the border show. +BASE_MAP_CREDIT = Markup("OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.") +ELEVATION_CREDIT = ( + "Terrain Tiles, accessed from https://registry.opendata.aws/terrain-tiles. " + "United States 3DEP (formerly NED) and global GMTED2010 and SRTM terrain data " + "courtesy of the U.S. Geological Survey. Canada terrain data contains " + "information licensed under the Open Government Licence - Canada. ArcticDEM " + "terrain data DEM(s) were created from DigitalGlobe, Inc., imagery and funded " + "under National Science Foundation awards 1043681, 1559691, and 1542736. " + "Global ETOPO1 terrain data U.S. National Oceanic and Atmospheric " + "Administration." +) +MAP_ELEVATION_CREDIT = ELEVATION_CREDIT + " Mexico terrain data source: INEGI, Continental relief, 2016." +# The trail maps' own caption line: the full credit of everything they can draw. +TRAIL_MAP_CREDIT = Markup(f"Base map: {BASE_MAP_CREDIT} Relief and contours: {esc(MAP_ELEVATION_CREDIT)}") +# The site footer's short form; the elevation figures on every list come from the same data. +FOOTER_MAP_CREDIT = Markup( + f"Base maps: {BASE_MAP_CREDIT} Elevation, relief and contours: Terrain Tiles, with data courtesy of " + "the U.S. Geological Survey, NOAA, ArcticDEM and INEGI; Canada terrain data under the Open Government " + "Licence - Canada. The full credit is under each trail map.") + SWATCH_LINE = Markup('') SWATCH_ROUTE = Markup('') SWATCH_ALT = Markup('') diff --git a/web/olt/layout.py b/web/olt/layout.py index 8227cce..cc082b9 100644 --- a/web/olt/layout.py +++ b/web/olt/layout.py @@ -18,7 +18,7 @@ scripts or styles (the Content-Security-Policy forbids them). import json import os -from . import site as site_settings +from . import common, site as site_settings from .markup import Markup, attrs, esc, json_block NAV = ( @@ -38,6 +38,11 @@ FONT_PRELOADS = ( ) MAPLIBRE_CSS = "/assets/vendor/maplibre-gl/maplibre-gl.css" MAPLIBRE_JS = "/assets/vendor/maplibre-gl/maplibre-gl.js" +# The outdoor map of the trail pages: its style, named on each trail map figure +# (data-outdoor) for app.js to fetch, and the contour add-on (maplibre-contour), +# loaded on those pages only (layout(outdoor=True)). +OUTDOOR_STYLE = "/assets/map/outdoor.json" +CONTOUR_JS = "/assets/vendor/maplibre-contour/maplibre-contour.js" def _current(path, href): @@ -113,7 +118,7 @@ def footer(site): """) @@ -124,7 +129,8 @@ def _ld_json_block(obj): return Markup(f'') -def layout(title, body, *, path, description="", maps=False, scripts=(), data=None, site=None, jsonld=None, og_type="website"): +def layout(title, body, *, path, description="", maps=False, outdoor=False, scripts=(), data=None, site=None, + jsonld=None, og_type="website"): """Return a complete HTML document. title the page's own title ("Arizona National Scenic Trail"); the site @@ -133,6 +139,8 @@ def layout(title, body, *, path, description="", maps=False, scripts=(), data=No path the page's site path, e.g. "/regions/" (canonical link, nav state). description meta description; defaults to the site tagline. maps True to load MapLibre (pages with a .mapfig[data-map]). + outdoor True as well on a page whose map is an outdoor map (a trail + page): loads the contour add-on after MapLibre, deferred. scripts extra same-origin script URLs, loaded with defer after app.js. data optional object, embedded as ') if maps: head.append(f'') + if outdoor: + head.append(f'') head += [f'' for s in scripts] data_block = json_block(data, "page-data") if data is not None else "" return f""" diff --git a/web/olt/pages.py b/web/olt/pages.py index d50e9e8..f183592 100644 --- a/web/olt/pages.py +++ b/web/olt/pages.py @@ -84,7 +84,7 @@ def render_site(records, out_dir, repo_root, site=None): title, description, body, needs_map = trail.render(rec, site, records) path = f"/trails/{rec['id']}/" layout.write_page(out_dir, path, layout.layout(title, body, path=path, description=description, - maps=needs_map, site=site)) + maps=needs_map, outdoor=needs_map, site=site)) pages += 1 dataset = seo.dataset_jsonld(records, site) body = home.render(records, site) diff --git a/web/olt/trail.py b/web/olt/trail.py index 4fd23d8..66bdeae 100644 --- a/web/olt/trail.py +++ b/web/olt/trail.py @@ -9,6 +9,7 @@ import re import urllib.parse from . import common, elevation, facets, hike, words +from .layout import OUTDOOR_STYLE from .markup import Markup, esc EXTRACT_SOURCES = {"osm": "OpenStreetMap", "usfs": "USDA Forest Service", "nps": "National Park Service"} @@ -307,7 +308,7 @@ def map_figure(rec): bbox = rec["derived"].get("map_bbox") or rec["derived"].get("bbox") bbox_attr = f' data-bbox="{",".join(str(v) for v in bbox)}"' if bbox else "" credit = common.sentence(common.credit_text(src.get("attribution", ""))) - return f"""
+ return f"""
@@ -319,7 +320,7 @@ def map_figure(rec):
    {legend}
-

Track: {esc(src.get("line_source", ""))}, read {esc(src.get("source_checked", ""))}, drawn simplified to 30 m. Credit: {esc(credit)} Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.

+

Track: {esc(src.get("line_source", ""))}, read {esc(src.get("source_checked", ""))}, drawn simplified to 30 m. Credit: {esc(credit)} {common.TRAIL_MAP_CREDIT}

""" @@ -476,7 +477,7 @@ def sketch_figure(rec): legend_text = "No GPX here: start only" _title, status, reason, rule, actions_html = _no_gpx_parts(rec) reason_html = reason if isinstance(reason, Markup) else common.rich(reason) - return f"""
+ return f"""
@@ -493,7 +494,7 @@ def sketch_figure(rec):

{reason_html}

{esc(rule)}

{actions_html} -

Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.

+

{common.TRAIL_MAP_CREDIT}

""" diff --git a/web/static/_headers b/web/static/_headers index 45350a9..5e7677c 100644 --- a/web/static/_headers +++ b/web/static/_headers @@ -14,15 +14,19 @@ # (web/tests/test_headers.py checks this against the built site). # Security headers for every response. No inline scripts or style elements: -# pages load same-origin scripts and styles, MapLibre runs from blob: workers, -# map images are self/data:/blob:, fonts are self-hosted, and tiles, glyphs and -# sprites are fetched from OpenFreeMap (connect-src). style-src-attr allows -# style="" attributes, which the pages use only to carry data to CSS (--km for -# the length strip, --n for the ratio bar, --pos for the verification gauge). +# pages load same-origin scripts and styles, MapLibre and the contour add-on +# run from blob: workers, map images are self/data:/blob:, fonts are +# self-hosted, and tiles, glyphs and sprites are fetched from OpenFreeMap +# (connect-src). The trail maps' relief and contours fetch elevation tiles +# (Terrain Tiles on AWS) with fetch(), from the page or the add-on's worker, +# which keeps this policy: connect-src allows that one path only, not all of +# s3.amazonaws.com. style-src-attr allows style="" attributes, which the +# pages use only to carry data to CSS (--km for the length strip, --n for the +# ratio bar, --pos for the verification gauge). /* X-Content-Type-Options: nosniff Referrer-Policy: strict-origin-when-cross-origin - Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; worker-src 'self' blob:; child-src 'self' blob:; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' https://tiles.openfreemap.org; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none' + Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; worker-src 'self' blob:; child-src 'self' blob:; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' https://tiles.openfreemap.org https://s3.amazonaws.com/elevation-tiles-prod/terrarium/; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none' # Site data. Matched by file type, not /data/*, so the pages under /data/ # (/data/, /data/schema/, /data/changelog/) revalidate like every other page. diff --git a/web/tests/test_extra.py b/web/tests/test_extra.py index 70543cb..96fdf1d 100644 --- a/web/tests/test_extra.py +++ b/web/tests/test_extra.py @@ -1,6 +1,7 @@ """Tests for the added pages: regions, routes, sources, logos, about, data, SEO files, the bulk archives and the response headers.""" import html +import json import os import re import subprocess @@ -334,6 +335,20 @@ class HeadersTest(unittest.TestCase): self.assertEqual(font_src.strip(), "'self'") self.assertIn("https://tiles.openfreemap.org", re.search(r"connect-src ([^;]*)", csp).group(1)) + def test_elevation_tiles_allowed_by_their_path_only(self): + """The outdoor map fetches Terrain Tiles (fetch() in the page or the + contour add-on's blob: worker): connect-src names that one path.""" + csp = self.headers("/trails/john-muir/").get("content-security-policy", "") + self.assertEqual(csp, self.headers("/").get("content-security-policy", "")) + connect = re.search(r"connect-src ([^;]*)", csp).group(1).split() + self.assertEqual(connect, ["'self'", "https://tiles.openfreemap.org", + "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/"]) + self.assertIn("worker-src 'self' blob:", csp) + self.assertIn("img-src 'self' data: blob:;", csp) + with open(os.path.join(WEB, "assets", "map", "outdoor.json"), encoding="utf-8") as f: + dem = json.load(f)["sources"]["olt-dem"]["tiles"][0] + self.assertTrue(dem.startswith(connect[2]), dem) + class SeoTest(unittest.TestCase): def test_sitemap_absent_without_base_url(self): diff --git a/web/tests/test_outdoor_map.py b/web/tests/test_outdoor_map.py new file mode 100644 index 0000000..24bbb8c --- /dev/null +++ b/web/tests/test_outdoor_map.py @@ -0,0 +1,225 @@ +"""The outdoor map of the trail pages: the style file, the contour add-on, where +each loads, and the credits. The security policy for the elevation tiles is +tested with the other headers in test_extra.py.""" +import ast +import json +import os +import re +import subprocess +import sys +import unittest + +WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +ROOT = os.path.dirname(WEB) +sys.path.insert(0, WEB) + +from olt import common, layout, records # noqa: E402 + +OUT = os.path.join(WEB, ".cache", "test-site") +STYLE = os.path.join(WEB, "assets", "map", "outdoor.json") +VENDOR = os.path.join(WEB, "assets", "vendor") +MAP_FONTS = {"Noto Sans Regular", "Noto Sans Italic", "Noto Sans Bold"} # served by OpenFreeMap + + +def setUpModule(): + os.makedirs(os.path.dirname(OUT), exist_ok=True) + subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT], + check=True, stdout=subprocess.DEVNULL) + + +def read(*parts): + with open(os.path.join(*parts), encoding="utf-8") as f: + return f.read() + + +def tool_constant(name): + """A constant of tools/elevation.py, read without importing it (the tool needs numpy).""" + tree = ast.parse(read(ROOT, "tools", "elevation.py")) + for node in tree.body: + if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in node.targets): + return ast.literal_eval(node.value) + raise KeyError(name) + + +def fonts(value): + """Every font stack named in a text-font value, expressions included.""" + if isinstance(value, list) and value and all(isinstance(v, str) for v in value) and value[0] != "literal": + return set(value) + if isinstance(value, list): + return set().union(*(fonts(v) for v in value)) if value else set() + return set() + + +class OutdoorStyleTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + with open(STYLE, encoding="utf-8") as f: + cls.style = json.load(f) + cls.layers = cls.style["layers"] + + def test_small_enough_to_read(self): + self.assertLess(os.path.getsize(STYLE), 40_000) + self.assertLess(len(self.layers), 60) + ids = [layer["id"] for layer in self.layers] + self.assertEqual(len(ids), len(set(ids))) + + def test_no_new_host_for_tiles_fonts_or_icons(self): + self.assertTrue(self.style["glyphs"].startswith("https://tiles.openfreemap.org/fonts/")) + self.assertTrue(self.style["sprite"].startswith("https://tiles.openfreemap.org/sprites/")) + self.assertEqual(self.style["sources"]["openmaptiles"]["url"], "https://tiles.openfreemap.org/planet") + for layer in self.layers: + self.assertIn(layer.get("source", "openmaptiles"), self.style["sources"], layer["id"]) + used = fonts(layer.get("layout", {}).get("text-font", [])) + self.assertLessEqual(used, MAP_FONTS, layer["id"]) + + def test_elevation_source_is_the_tools_dataset_capped(self): + dem = self.style["sources"]["olt-dem"] + self.assertEqual(dem["type"], "raster-dem") + self.assertEqual(dem["encoding"], "terrarium") + self.assertEqual(dem["tiles"], [tool_constant("TILE_URL")]) + self.assertLessEqual(dem["maxzoom"], 12) + self.assertIn("Terrain Tiles", dem["attribution"]) + self.assertIn("https://registry.opendata.aws/terrain-tiles/", dem["attribution"]) + # Bounded to North America, where the credit under the map covers every source drawn. + west, south, east, north = dem["bounds"] + self.assertLessEqual(west, -170) + self.assertGreaterEqual(south, 10) + self.assertLessEqual(east, -50) + self.assertEqual(self.style["sources"]["olt-contours"]["bounds"], dem["bounds"]) + + def test_contours_only_when_zoomed_in_with_round_steps(self): + contours = self.style["metadata"]["olt:contours"] + source = self.style["sources"]["olt-contours"] + self.assertGreaterEqual(source["minzoom"], 11) + self.assertEqual(sorted(contours), ["ft", "m"]) + self.assertAlmostEqual(contours["ft"]["multiplier"], 3.28084) + self.assertEqual(contours["m"]["multiplier"], 1) + for unit, opts in contours.items(): + zooms = sorted(int(z) for z in opts["thresholds"]) + self.assertEqual(zooms[0], source["minzoom"], unit) + steps = [opts["thresholds"][str(z)] for z in zooms] + for minor, major in steps: + self.assertEqual(major % minor, 0, unit) + self.assertEqual(minor % 10, 0, unit) + # Closer lines as the map zooms in, never wider. + self.assertEqual([s[0] for s in steps], sorted((s[0] for s in steps), reverse=True), unit) + + def test_dark_and_km_values_have_light_and_miles_ones(self): + dark = km = 0 + for layer in self.layers: + meta = layer.get("metadata", {}) + for prop in meta.get("olt:dark", {}): + dark += 1 + self.assertFalse(prop.startswith(("text-field", "visibility")), layer["id"]) + if prop != "icon-opacity": + self.assertIn(prop, layer.get("paint", {}), f"{layer['id']} {prop}") + for prop in meta.get("olt:km", {}): + km += 1 + self.assertIn(prop, layer.get("layout", {}), f"{layer['id']} {prop}") + self.assertGreater(dark, 30) + self.assertEqual(km, 2) # the peak heights and the contour labels + + def test_peaks_and_contours_name_their_units(self): + by_id = {layer["id"]: layer for layer in self.layers} + peak, label = by_id["peak"], by_id["contour-label"] + self.assertIn('"ele_ft"', json.dumps(peak["layout"]["text-field"])) + self.assertIn('" ft"', json.dumps(peak["layout"]["text-field"])) + self.assertIn('" m"', json.dumps(peak["metadata"]["olt:km"]["text-field"])) + self.assertIn('" ft"', json.dumps(label["layout"]["text-field"])) + self.assertIn('" m"', json.dumps(label["metadata"]["olt:km"]["text-field"])) + + def test_footpaths_are_thin_dashes(self): + by_id = {layer["id"]: layer for layer in self.layers} + for lid in ("road-path", "road-track"): + paint = by_id[lid]["paint"] + self.assertIn("line-dasharray", paint, lid) + widths = paint["line-width"][3:] + self.assertLessEqual(max(widths[1::2]), 2, lid) + + def test_licence_notices_beside_the_style(self): + text = read(WEB, "assets", "map", "LICENSE.txt") + text = " ".join(text.split()) + for words in ("OpenFreeMap", "MIT License", "OSM Liberty", "BSD 3-Clause", + "Creative Commons Attribution 4.0", "OpenMapTiles"): + self.assertIn(words, text) + + +class ContourAddOnTest(unittest.TestCase): + def test_vendored_with_its_licence_and_pinned(self): + script = os.path.join(VENDOR, "maplibre-contour", "maplibre-contour.js") + self.assertTrue(os.path.isfile(script)) + self.assertIn("BSD 3-Clause License", read(VENDOR, "maplibre-contour", "LICENSE.txt")) + readme = read(VENDOR, "README.md") + self.assertIn("| maplibre-contour | 0.1.1 |", readme) + import hashlib + with open(script, "rb") as f: + digest = hashlib.sha256(f.read()).hexdigest() + self.assertIn(f"{digest} maplibre-contour.js", readme) + self.assertNotIn("sourceMappingURL", read(script)) + + +class OutdoorPagesTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.records = records.load_records(ROOT) + + def test_trail_maps_are_outdoor_and_load_the_add_on(self): + contour = f'' + maplibre = f'' + with_map = 0 + for rec in self.records: + page = read(OUT, "trails", rec["id"], "index.html") + figures = re.findall(r'
]*>', page) + mapped = [f for f in figures if 'data-map="' in f] + if mapped: + with_map += 1 + for fig in mapped: + self.assertIn(f'data-outdoor="{layout.OUTDOOR_STYLE}"', fig, rec["id"]) + self.assertEqual(page.count(contour), 1, rec["id"]) + self.assertLess(page.index(maplibre), page.index(contour), rec["id"]) + else: + self.assertNotIn(contour, page, rec["id"]) + self.assertNotIn("data-outdoor", page, rec["id"]) + self.assertGreater(with_map, 100) + self.assertTrue(os.path.isfile(os.path.join(OUT, *layout.OUTDOOR_STYLE.strip("/").split("/")))) + self.assertTrue(os.path.isfile(os.path.join(OUT, *layout.CONTOUR_JS.strip("/").split("/")))) + + def test_overview_maps_stay_plain(self): + paths = ["index.html", os.path.join("routes", "index.html"), os.path.join("lists", "index.html")] + for base in ("regions", "lists"): + for name in sorted(os.listdir(os.path.join(OUT, base))): + if os.path.isfile(os.path.join(OUT, base, name, "index.html")): + paths.append(os.path.join(base, name, "index.html")) + overview = 0 + for path in paths: + page = read(OUT, path) + overview += 'data-map="overview"' in page + self.assertNotIn(layout.CONTOUR_JS, page, path) + self.assertNotIn("data-outdoor", page, path) + self.assertGreater(overview, 10) + + +class CreditsTest(unittest.TestCase): + def test_elevation_credit_is_the_tools_credit(self): + self.assertEqual(common.ELEVATION_CREDIT, tool_constant("ATTRIBUTION")) + self.assertTrue(common.MAP_ELEVATION_CREDIT.startswith(common.ELEVATION_CREDIT)) + self.assertIn("INEGI", common.MAP_ELEVATION_CREDIT) + + def test_every_trail_map_credits_the_base_map_and_the_relief(self): + credit = str(common.TRAIL_MAP_CREDIT) + self.assertIn("Relief and contours: Terrain Tiles, accessed from https://registry.opendata.aws/terrain-tiles.", credit) + for rec in records.load_records(ROOT): + page = read(OUT, "trails", rec["id"], "index.html") + if 'data-map="' in page: + caption = page[page.index('
")] + self.assertIn(credit, caption, rec["id"]) + + def test_footer_credits_the_elevation_data_on_every_page(self): + for base, _, names in os.walk(OUT): + for name in names: + if name.endswith(".html"): + page = read(base, name) + foot = page[page.index('