Give trail pages an outdoor map
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

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 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-15 13:26:45 -07:00
1 parent 540a3220be
commit ad2223f427
15 files changed
+994 -27

No files matched your search

+225 -11
View File
@@ -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'));
+73
View File
@@ -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.
+256
View File
@@ -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: <a href=\"https://registry.opendata.aws/terrain-tiles/\">Terrain Tiles</a>, 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)"}}}
]
}
+4 -1
View File
@@ -1,5 +1,6 @@
/* Runs in <head>, 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 */ }
})();
+16
View File
@@ -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;
+40 -1
View File
@@ -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
+72
View File
@@ -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.
+15
View File
@@ -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;f<n.height+a;f++){c=n.get(0,f-1),u=n.get(0,f);let s=Math.min(c,u),o=Math.max(c,u);for(p=1-a;p<n.width+a;p++){l=c,d=u,c=n.get(p,f-1),u=n.get(p,f);const a=s,h=o;if(s=Math.min(c,u),o=Math.max(c,u),isNaN(l)||isNaN(c)||isNaN(u)||isNaN(d))continue;const y=Math.min(a,s),v=Math.max(h,o),x=Math.ceil(y/t)*t,P=Math.floor(v/t)*t;for(let s=x;s<=P;s+=t){const t=l>s,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);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(i[r[s]]=t[r[s]])}return i}function a(t,e,i,r){return new(i||(i=Promise))((function(s,n){function o(t){try{h(r.next(t))}catch(t){n(t)}}function a(t){try{h(r.throw(t))}catch(t){n(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((r=r.apply(t,e||[])).next())}))}function h(t){const e=Object.entries(t);return e.sort((([t],[e])=>t<e?-1:t>e?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.lastUsed<e&&(e=i.lastUsed,t=r)})),void 0!==t&&this.items.delete(t)}}}function k(t,e){return b||(b=new OffscreenCanvas(t.width,t.height),y=b.getContext("2d",{willReadFrequently:!0})),M(t,e,b,y)}const V=function(){if(null==p&&(p=!1,f()&&"undefined"!=typeof VideoFrame)){const t=5,e=new OffscreenCanvas(5,5).getContext("2d",{willReadFrequently:!0});if(e){for(let i=0;i<t*t;i++){const r=4*i;e.fillStyle=`rgb(${r},${r+1},${r+2})`,e.fillRect(i%t,Math.floor(i/t),1,1)}const i=e.getImageData(0,0,t,t).data;for(let e=0;e<t*t*4;e++)if(e%4!=3&&i[e]!==e){p=!0;break}}}return p||!1}()?function(t,e,i){return a(this,void 0,void 0,(function*(){var r,s,n;const o=yield createImageBitmap(t);if(m(i))return null;const a=new VideoFrame(o,{timestamp:0});try{if(!((null===(r=null==a?void 0:a.format)||void 0===r?void 0:r.startsWith("BGR"))||(null===(s=null==a?void 0:a.format)||void 0===s?void 0:s.startsWith("RGB"))))throw new Error(`Unrecognized format: ${null==a?void 0:a.format}`);const t=null===(n=null==a?void 0:a.format)||void 0===n?void 0:n.startsWith("BGR"),i=a.allocationSize(),h=new Uint8ClampedArray(i);if(yield a.copyTo(h),t)for(let t=0;t<h.length;t+=4){const e=h[t];h[t]=h[t+2],h[t+2]=e}return S(o.width,o.height,e,h)}catch(t){return m(i)?null:k(o,e)}finally{a.close()}}))}:f()?function(t,e,i){return a(this,void 0,void 0,(function*(){const r=yield createImageBitmap(t);return m(i)?null:k(r,e)}))}:"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope?function(t,e,i){return self.actor.send("decodeImage",[],i,void 0,t,e)}:function(t,e,i){return a(this,void 0,void 0,(function*(){v||(v=document.createElement("canvas"),x=v.getContext("2d",{willReadFrequently:!0}));const r=new Image;g(i,(()=>r.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<r.length;t+=4)n[t/4]=s(r[t],r[t+1],r[t+2]);return{width:t,height:e,data:n}}class T{constructor(t,e,i){this.split=(t,e,i)=>{if(0===t)return this;const r=1<<t,s=e*this.width/r,n=i*this.height/r;return new T(this.width/r,this.height/r,((t,e)=>this.get(t+s,e+n)))},this.subsamplePixelCenters=t=>{const e=(t,e,i)=>isNaN(t)?e:isNaN(e)?t:t+(e-t)*iLine truncated
+24
View File
@@ -183,6 +183,30 @@ def plate(rec, *, size="", link=False, eager=False, alt=None):
return Markup(f'<div class="{cls} plate--none" aria-hidden="true"><span>{inner}</span></div>')
# 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, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;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('<span class="swatch swatch--line" aria-hidden="true"></span>')
SWATCH_ROUTE = Markup('<span class="swatch swatch--route" aria-hidden="true"></span>')
SWATCH_ALT = Markup('<span class="swatch swatch--alt" aria-hidden="true"></span>')
+13 -3
View File
@@ -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):
</div>
</div>
<div class="site-footer__base">
<div class="container">Base maps: OpenFreeMap, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;OpenStreetMap contributors.</div>
<div class="container">{common.FOOTER_MAP_CREDIT}</div>
</div>
</footer>""")
@@ -124,7 +129,8 @@ def _ld_json_block(obj):
return Markup(f'<script type="application/ld+json">{text}</script>')
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 <script type="application/json" id="page-data">.
site settings (olt.site.Site); defaults to web/site.toml.
@@ -187,6 +195,8 @@ def layout(title, body, *, path, description="", maps=False, scripts=(), data=No
head.append('<script src="/assets/app.js" defer></script>')
if maps:
head.append(f'<script src="{MAPLIBRE_JS}" defer></script>')
if outdoor:
head.append(f'<script src="{CONTOUR_JS}" defer></script>')
head += [f'<script src="{esc(s)}" defer></script>' for s in scripts]
data_block = json_block(data, "page-data") if data is not None else ""
return f"""<!doctype html>
+1 -1
View File
@@ -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)
+5 -4
View File
@@ -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"""<figure class="mapfig mapfig--detail detail__map" data-map="trail" data-src="/trails/{esc(rec["id"])}/map.json" data-route="{"yes" if route else "no"}"{bbox_attr}>
return f"""<figure class="mapfig mapfig--detail detail__map" data-map="trail" data-src="/trails/{esc(rec["id"])}/map.json" data-route="{"yes" if route else "no"}"{bbox_attr} data-outdoor="{OUTDOOR_STYLE}">
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
<div class="map" role="region" aria-label="Map of the {esc(rec["name"])}">
@@ -319,7 +320,7 @@ def map_figure(rec):
</div>
<figcaption class="mapfig__caption">
<ul class="legend" aria-label="Legend">{legend}</ul>
<p>Track: {esc(src.get("line_source", ""))}, read {esc(src.get("source_checked", ""))}, drawn simplified to 30&nbsp;m. Credit: {esc(credit)} Base map: OpenFreeMap, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;OpenStreetMap contributors.</p>
<p>Track: {esc(src.get("line_source", ""))}, read {esc(src.get("source_checked", ""))}, drawn simplified to 30&nbsp;m. Credit: {esc(credit)} {common.TRAIL_MAP_CREDIT}</p>
</figcaption>
</figure>"""
@@ -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"""<figure class="mapfig mapfig--detail detail__map" id="track" data-map="sketch" data-src="/trails/{esc(rec["id"])}/sketch.json" data-route="{"yes" if route else "no"}"{bbox_attr}>
return f"""<figure class="mapfig mapfig--detail detail__map" id="track" data-map="sketch" data-src="/trails/{esc(rec["id"])}/sketch.json" data-route="{"yes" if route else "no"}"{bbox_attr} data-outdoor="{OUTDOOR_STYLE}">
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
<div class="map" role="region" aria-label="Map showing the start and end of the {esc(rec["name"])}; no GPX here">
@@ -493,7 +494,7 @@ def sketch_figure(rec):
<p>{reason_html}</p>
<p class="note">{esc(rule)}</p>
{actions_html}
<p>Base map: OpenFreeMap, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;OpenStreetMap contributors.</p>
<p>{common.TRAIL_MAP_CREDIT}</p>
</div>
</figcaption>
</figure>"""
+10 -6
View File
@@ -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.
+15
View File
@@ -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):
+225
View File
@@ -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'<script src="{layout.CONTOUR_JS}" defer></script>'
maplibre = f'<script src="{layout.MAPLIBRE_JS}" defer></script>'
with_map = 0
for rec in self.records:
page = read(OUT, "trails", rec["id"], "index.html")
figures = re.findall(r'<figure class="mapfig[^"]*"[^>]*>', 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('<figcaption class="mapfig__caption'):]
caption = caption[:caption.index("</figcaption>")]
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('<div class="site-footer__base">'):]
self.assertIn("Terrain Tiles", foot, os.path.join(base, name))
self.assertIn("OpenFreeMap", foot, os.path.join(base, name))