web/ is a static site generator for the dataset, in Python's standard library only. `python3 web/build.py --out _site` writes a page for each of the 138 records, a finder on the home page with a map of the 85 lines, region and route indexes, and the repository's documents as pages. Each line is offered as the record's GeoJSON and as a GPX simplified to 5 m, with two archives of everything. The site's name and address are set in web/site.toml: Long Hikes, at https://longhikes.org. The dataset keeps its own name. netlify.toml and web/static/_headers configure the Netlify site (content types, download dispositions, caching, a content security policy with no inline script). It is deployed with the Netlify CLI from a local build, because Netlify cannot build from this forge. MapLibre GL JS and the two typefaces are vendored under web/assets/; map tiles come from OpenFreeMap. Tests: python3 -m unittest discover -s web/tests (164). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
No files matched your search
@@ -0,0 +1,796 @@
|
||||
/* 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)
|
||||
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.
|
||||
3. Trail finder (home page): search, filters, sort, URL query state, map/list highlight
|
||||
4. Copy-credit buttons
|
||||
|
||||
Every page works without this script: the list holds every record and each map
|
||||
frame keeps its size, border and caption. */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var root = document.documentElement;
|
||||
var darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
var KM_PER_MI = 1.609344;
|
||||
var fmt = new Intl.NumberFormat('en-US');
|
||||
|
||||
/* 1. Preferences ----------------------------------------------------------- */
|
||||
|
||||
function readPref(key) {
|
||||
try { return localStorage.getItem(key); } catch (e) { return null; }
|
||||
}
|
||||
function writePref(key, value) {
|
||||
try {
|
||||
if (value) localStorage.setItem(key, value);
|
||||
else localStorage.removeItem(key);
|
||||
} catch (e) { /* storage blocked: the choice lasts for this page only */ }
|
||||
}
|
||||
|
||||
function isDark() {
|
||||
var t = root.dataset.theme;
|
||||
return t ? t === 'dark' : darkQuery.matches;
|
||||
}
|
||||
function milesFirst() { return root.dataset.units === 'mi'; }
|
||||
|
||||
function setTheme(value) {
|
||||
if (value === 'light' || value === 'dark') root.dataset.theme = value;
|
||||
else delete root.dataset.theme;
|
||||
writePref('lh-theme', value === 'light' || value === 'dark' ? value : null);
|
||||
document.dispatchEvent(new Event('olt:theme'));
|
||||
}
|
||||
|
||||
function setUnits(value) {
|
||||
if (value === 'mi') root.dataset.units = 'mi';
|
||||
else delete root.dataset.units;
|
||||
writePref('lh-units', value === 'mi' ? 'mi' : null);
|
||||
syncRadios('input[name="units"], input[name="units-list"]', value === 'mi' ? 'mi' : 'km');
|
||||
document.dispatchEvent(new Event('olt:units'));
|
||||
}
|
||||
|
||||
function syncRadios(selector, value) {
|
||||
document.querySelectorAll(selector).forEach(function (input) { input.checked = input.value === value; });
|
||||
}
|
||||
|
||||
syncRadios('input[name="theme"]', readPref('lh-theme') || 'auto');
|
||||
syncRadios('input[name="units"], input[name="units-list"]', milesFirst() ? 'mi' : 'km');
|
||||
document.querySelectorAll('input[name="theme"]').forEach(function (input) {
|
||||
input.addEventListener('change', function () { if (input.checked) setTheme(input.value); });
|
||||
});
|
||||
document.querySelectorAll('input[name="units"], input[name="units-list"]').forEach(function (input) {
|
||||
input.addEventListener('change', function () { if (input.checked) setUnits(input.value); });
|
||||
});
|
||||
darkQuery.addEventListener('change', function () {
|
||||
if (!root.dataset.theme) document.dispatchEvent(new Event('olt:theme'));
|
||||
});
|
||||
|
||||
/* A length in both units, in the reader's order: "1,287 km (800 mi)". */
|
||||
function lengthText(km) {
|
||||
var k = fmt.format(km) + ' km';
|
||||
var m = fmt.format(Math.round(km / KM_PER_MI)) + ' mi';
|
||||
return milesFirst() ? m + ' (' + k + ')' : k + ' (' + m + ')';
|
||||
}
|
||||
|
||||
/* Resolve a colour token (light-dark() included) to an rgb() string. */
|
||||
var probe = null;
|
||||
function token(name) {
|
||||
if (!probe) {
|
||||
probe = document.createElement('span');
|
||||
probe.hidden = true;
|
||||
document.body.appendChild(probe);
|
||||
}
|
||||
probe.style.color = 'var(' + name + ')';
|
||||
return getComputedStyle(probe).color;
|
||||
}
|
||||
|
||||
/* 2. Maps ------------------------------------------------------------------- */
|
||||
|
||||
var STYLE_URL = 'https://tiles.openfreemap.org/styles/positron';
|
||||
|
||||
function linesOf(feature) {
|
||||
var g = feature.geometry || {};
|
||||
if (g.type === 'LineString') return [g.coordinates];
|
||||
return g.type === 'MultiLineString' ? g.coordinates : [];
|
||||
}
|
||||
|
||||
function bboxOf(fc) {
|
||||
if (fc.bbox && fc.bbox.length === 4) return fc.bbox;
|
||||
var b = [180, 90, -180, -90];
|
||||
fc.features.forEach(function (f) {
|
||||
linesOf(f).forEach(function (line) {
|
||||
line.forEach(function (p) {
|
||||
if (p[0] < b[0]) b[0] = p[0];
|
||||
if (p[1] < b[1]) b[1] = p[1];
|
||||
if (p[0] > b[2]) b[2] = p[0];
|
||||
if (p[1] > b[3]) b[3] = p[1];
|
||||
});
|
||||
});
|
||||
});
|
||||
return b;
|
||||
}
|
||||
|
||||
function bboxOfFeature(feature) {
|
||||
var b = [180, 90, -180, -90];
|
||||
var seen = false;
|
||||
linesOf(feature).forEach(function (line) {
|
||||
line.forEach(function (p) {
|
||||
seen = true;
|
||||
if (p[0] < b[0]) b[0] = p[0];
|
||||
if (p[1] < b[1]) b[1] = p[1];
|
||||
if (p[0] > b[2]) b[2] = p[0];
|
||||
if (p[1] > b[3]) b[3] = p[1];
|
||||
});
|
||||
});
|
||||
return seen ? b : null;
|
||||
}
|
||||
|
||||
function mercY(lat) { return Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360)); }
|
||||
function invMercY(y) { return (360 / Math.PI) * Math.atan(Math.exp(y)) - 90; }
|
||||
|
||||
function dms(value, pos, neg) {
|
||||
var a = Math.abs(value);
|
||||
var d = Math.floor(a);
|
||||
var m = Math.round((a - d) * 60);
|
||||
if (m === 60) { d += 1; m = 0; }
|
||||
return d + '°' + (m < 10 ? '0' : '') + m + '′' + (value >= 0 ? pos : neg);
|
||||
}
|
||||
|
||||
/* Lines on a plain graticule (Web Mercator), no tiles. Returns the drawn extent. */
|
||||
function drawFallback(host, fc, bbox, routeMain) {
|
||||
var rect = host.getBoundingClientRect();
|
||||
var W = Math.max(Math.round(rect.width), 280);
|
||||
var H = Math.max(Math.round(rect.height), 180);
|
||||
var pad = 28;
|
||||
var rad = Math.PI / 180;
|
||||
var cx = (bbox[0] + bbox[2]) / 2;
|
||||
var y0 = mercY(bbox[1]);
|
||||
var y1 = mercY(bbox[3]);
|
||||
var cy = (y0 + y1) / 2;
|
||||
var k = Math.min((W - 2 * pad) / Math.max((bbox[2] - bbox[0]) * rad, 1e-6),
|
||||
(H - 2 * pad) / Math.max(y1 - y0, 1e-6));
|
||||
function x(lon) { return W / 2 + (lon - cx) * rad * k; }
|
||||
function y(lat) { return H / 2 - (mercY(lat) - cy) * k; }
|
||||
var ext = { w: cx - W / 2 / k / rad, e: cx + W / 2 / k / rad, n: invMercY(cy + H / 2 / k), s: invMercY(cy - H / 2 / k) };
|
||||
|
||||
var span = Math.max(ext.e - ext.w, ext.n - ext.s);
|
||||
var step = [0.25, 0.5, 1, 2, 5, 10, 15].filter(function (s) { return span / s <= 9; })[0] || 20;
|
||||
var grat = '';
|
||||
for (var lon = Math.ceil(ext.w / step) * step; lon <= ext.e; lon += step) grat += 'M' + x(lon).toFixed(1) + ' 0V' + H;
|
||||
for (var lat = Math.ceil(ext.s / step) * step; lat <= ext.n; lat += step) grat += 'M0 ' + y(lat).toFixed(1) + 'H' + W;
|
||||
|
||||
var ns = 'http://www.w3.org/2000/svg';
|
||||
var svg = document.createElementNS(ns, 'svg');
|
||||
svg.setAttribute('viewBox', '0 0 ' + W + ' ' + H);
|
||||
svg.setAttribute('preserveAspectRatio', 'xMidYMid slice');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
svg.setAttribute('focusable', 'false');
|
||||
function path(cls, d, id) {
|
||||
var p = document.createElementNS(ns, 'path');
|
||||
p.setAttribute('class', cls);
|
||||
p.setAttribute('d', d);
|
||||
if (id) p.setAttribute('data-id', id);
|
||||
svg.appendChild(p);
|
||||
}
|
||||
path('fallback__grat', grat);
|
||||
var drawn = fc.features.map(function (f) {
|
||||
var d = linesOf(f).map(function (line) {
|
||||
return 'M' + line.map(function (p) { return x(p[0]).toFixed(1) + ' ' + y(p[1]).toFixed(1); }).join('L');
|
||||
}).join('');
|
||||
var p = f.properties || {};
|
||||
var mod = p.role === 'alternate' ? ' fallback__line--alternate'
|
||||
: (p.kind === 'route' || (routeMain && p.role === 'main')) ? ' fallback__line--route' : '';
|
||||
return { d: d, mod: mod, id: p.id || '' };
|
||||
});
|
||||
drawn.forEach(function (l) { path('fallback__casing', l.d, l.id); });
|
||||
drawn.forEach(function (l) { path('fallback__line' + l.mod, l.d, l.id); });
|
||||
host.replaceChildren(svg);
|
||||
return ext;
|
||||
}
|
||||
|
||||
function webglAvailable() {
|
||||
try {
|
||||
var c = document.createElement('canvas');
|
||||
return !!(c.getContext('webgl2') || c.getContext('webgl'));
|
||||
} catch (e) { return false; }
|
||||
}
|
||||
|
||||
/* Night version of the Positron base map: invert lightness, keep hue. */
|
||||
var COLOR_PROPS = ['background-color', 'fill-color', 'fill-outline-color', 'line-color', 'text-color', 'text-halo-color'];
|
||||
var ctx2d = null;
|
||||
|
||||
function parseColor(str) {
|
||||
if (typeof str !== 'string' || !/^(#|rgb|hsl)/i.test(str.trim())) return null;
|
||||
if (!ctx2d) ctx2d = document.createElement('canvas').getContext('2d');
|
||||
ctx2d.fillStyle = '#000';
|
||||
ctx2d.fillStyle = str;
|
||||
var v = ctx2d.fillStyle;
|
||||
var m;
|
||||
if (v.charAt(0) === '#') return [parseInt(v.slice(1, 3), 16), parseInt(v.slice(3, 5), 16), parseInt(v.slice(5, 7), 16), 1];
|
||||
if ((m = v.match(/rgba?\(([^)]+)\)/))) {
|
||||
var parts = m[1].split(',').map(Number);
|
||||
return [parts[0], parts[1], parts[2], parts.length > 3 ? parts[3] : 1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toHsl(r, g, b) {
|
||||
r /= 255; g /= 255; b /= 255;
|
||||
var max = Math.max(r, g, b), min = Math.min(r, g, b), l = (max + min) / 2, h = 0, s = 0;
|
||||
if (max !== min) {
|
||||
var d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
|
||||
h *= 60;
|
||||
}
|
||||
return [h, s, l];
|
||||
}
|
||||
|
||||
function nightColor(value, prop, layerId) {
|
||||
if (Array.isArray(value)) return value.map(function (v) { return nightColor(v, prop, layerId); });
|
||||
if (value && typeof value === 'object') {
|
||||
var out = {};
|
||||
Object.keys(value).forEach(function (k) { out[k] = nightColor(value[k], prop, layerId); });
|
||||
return out;
|
||||
}
|
||||
var c = parseColor(value);
|
||||
if (!c) return value;
|
||||
if (layerId === 'water') return 'hsla(205, 22%, 6%, ' + c[3] + ')';
|
||||
var hsl = toHsl(c[0], c[1], c[2]);
|
||||
var l = prop === 'text-color' ? 0.92 - hsl[2] * 0.55 : 0.07 + (1 - hsl[2]) * 0.55;
|
||||
return 'hsla(' + hsl[0].toFixed(0) + ', ' + (hsl[1] * 80).toFixed(0) + '%, ' + (l * 100).toFixed(1) + '%, ' + c[3] + ')';
|
||||
}
|
||||
|
||||
function tintBasemap(map, originals) {
|
||||
var dark = isDark();
|
||||
map.getStyle().layers.forEach(function (layer) {
|
||||
if (layer.id.indexOf('olt-') === 0) return;
|
||||
COLOR_PROPS.forEach(function (prop) {
|
||||
var key = layer.id + '|' + prop;
|
||||
if (!(key in originals)) {
|
||||
try { originals[key] = map.getPaintProperty(layer.id, prop); } catch (e) { originals[key] = undefined; }
|
||||
}
|
||||
var orig = originals[key];
|
||||
if (orig === undefined) return;
|
||||
try { map.setPaintProperty(layer.id, prop, dark ? nightColor(orig, prop, layer.id) : orig); } catch (e) { /* no such property */ }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function layerDefs(kind, routeMain) {
|
||||
if (kind === 'overview') {
|
||||
return [
|
||||
{ id: 'olt-casing', color: '--casing', width: [3, 4, 9, 9] },
|
||||
{ id: 'olt-hi', color: '--ink', width: [3, 7, 9, 11], filter: ['==', ['get', 'id'], ''] },
|
||||
{ id: 'olt-line', color: '--trail', width: [3, 1.6, 9, 4], filter: ['!=', ['get', 'kind'], 'route'], hit: true },
|
||||
{ id: 'olt-route', color: '--route', width: [3, 1.6, 9, 4], dash: [1.6, 1.1], filter: ['==', ['get', 'kind'], 'route'], hit: true }
|
||||
];
|
||||
}
|
||||
return [
|
||||
{ id: 'olt-casing', color: '--casing', width: [5, 4, 12, 8] },
|
||||
{ id: 'olt-alt', color: '--trail', width: [5, 1.5, 12, 3], dash: [2, 1.6], filter: ['==', ['get', 'role'], 'alternate'] },
|
||||
{ id: 'olt-main', color: routeMain ? '--route' : '--trail', width: [5, 2.5, 12, 5],
|
||||
dash: routeMain ? [2, 1.2] : null, filter: ['==', ['get', 'role'], 'main'] }
|
||||
];
|
||||
}
|
||||
|
||||
/* Trail lines go under the base map's labels, as on a printed map. */
|
||||
function addLineLayers(map, fc, defs) {
|
||||
var firstLabel = map.getStyle().layers.filter(function (l) { return l.type === 'symbol'; })[0];
|
||||
map.addSource('olt', { type: 'geojson', data: fc });
|
||||
defs.forEach(function (def) {
|
||||
var layer = {
|
||||
id: def.id,
|
||||
type: 'line',
|
||||
source: 'olt',
|
||||
layout: { 'line-join': 'round', 'line-cap': def.dash ? 'butt' : 'round' },
|
||||
paint: {
|
||||
'line-color': token(def.color),
|
||||
'line-width': ['interpolate', ['linear'], ['zoom'], def.width[0], def.width[1], def.width[2], def.width[3]]
|
||||
}
|
||||
};
|
||||
if (def.dash) layer.paint['line-dasharray'] = def.dash;
|
||||
if (def.filter) layer.filter = def.filter;
|
||||
map.addLayer(layer, firstLabel && firstLabel.id);
|
||||
});
|
||||
}
|
||||
|
||||
var maps = [];
|
||||
var mapStarters = [];
|
||||
|
||||
function initMap(fig) {
|
||||
var host = fig.querySelector('.map');
|
||||
var fallback = host.querySelector('.map__fallback');
|
||||
var status = host.querySelector('.map__status');
|
||||
var nw = fig.querySelector('.mapfig__corner--nw');
|
||||
var se = fig.querySelector('.mapfig__corner--se');
|
||||
var kind = fig.dataset.map;
|
||||
var routeMain = fig.dataset.route === 'yes';
|
||||
var defs = layerDefs(kind, routeMain);
|
||||
var onlyIds = (fig.dataset.ids || '').trim().split(/\s+/).filter(Boolean);
|
||||
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 };
|
||||
maps.push(entry);
|
||||
|
||||
var bbox = (fig.dataset.bbox || '').split(',').map(Number);
|
||||
if (bbox.length !== 4 || bbox.some(isNaN)) bbox = null;
|
||||
|
||||
function corners(ext) {
|
||||
if (nw) nw.textContent = dms(ext.n, 'N', 'S') + ' ' + dms(ext.w, 'E', 'W');
|
||||
if (se) se.textContent = dms(ext.s, 'N', 'S') + ' ' + dms(ext.e, 'E', 'W');
|
||||
}
|
||||
function redrawFallback() {
|
||||
if (!entry.ready && entry.fc) {
|
||||
corners(drawFallback(fallback, entry.fc, bbox || bboxOf(entry.fc), routeMain));
|
||||
if (entry.visibleIds) setVisible(entry, entry.visibleIds);
|
||||
}
|
||||
}
|
||||
function fail(reason) {
|
||||
if (entry.ready) return;
|
||||
host.dataset.state = 'fallback';
|
||||
status.textContent = 'Base map unavailable (' + reason + '). The line is drawn on a plain graticule.';
|
||||
}
|
||||
|
||||
status.textContent = 'Loading the line…';
|
||||
var dataReady = fetch(fig.dataset.src, { credentials: 'same-origin' })
|
||||
.then(function (r) {
|
||||
if (!r.ok) throw new Error(r.status);
|
||||
return r.json();
|
||||
})
|
||||
.then(function (fc) {
|
||||
entry.fc = fc;
|
||||
bbox = bbox || bboxOf(fc);
|
||||
entry.fullBounds = bbox.slice();
|
||||
if (kind === 'overview') {
|
||||
entry.boundsById = {};
|
||||
fc.features.forEach(function (f) {
|
||||
var id = (f.properties || {}).id;
|
||||
var fb = id && bboxOfFeature(f);
|
||||
if (fb) entry.boundsById[id] = fb;
|
||||
});
|
||||
}
|
||||
if (!entry.ready && entry.mapStarted && window.maplibregl) status.textContent = 'Loading the base map…';
|
||||
redrawFallback();
|
||||
return fc;
|
||||
})
|
||||
.catch(function () {
|
||||
host.dataset.state = 'error';
|
||||
status.textContent = 'The line data did not load. Downloads on this page are unaffected.';
|
||||
return null;
|
||||
});
|
||||
|
||||
var resizeTimer;
|
||||
window.addEventListener('resize', function () {
|
||||
clearTimeout(resizeTimer);
|
||||
resizeTimer = setTimeout(redrawFallback, 150);
|
||||
});
|
||||
|
||||
/* The MapLibre half of the map. Everything above (the fetch and the
|
||||
fallback drawing) runs as soon as this script does; this part waits
|
||||
until MapLibre is present (see startMaps below), because the page loads
|
||||
this script before the MapLibre script. If it never arrives the
|
||||
fallback drawing stays and fail() says why. */
|
||||
function startMapLibre() {
|
||||
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 options = {
|
||||
container: host.querySelector('.map__canvas'),
|
||||
style: STYLE_URL,
|
||||
attributionControl: { compact: true },
|
||||
cooperativeGestures: true,
|
||||
dragRotate: false,
|
||||
pitchWithRotate: false,
|
||||
touchPitch: false
|
||||
};
|
||||
if (bbox) {
|
||||
options.bounds = [[bbox[0], bbox[1]], [bbox[2], bbox[3]]];
|
||||
options.fitBoundsOptions = { padding: 32 };
|
||||
}
|
||||
var map = new maplibregl.Map(options);
|
||||
entry.map = map;
|
||||
map.touchZoomRotate.disableRotation();
|
||||
map.addControl(new maplibregl.NavigationControl({ showCompass: false }), 'top-right');
|
||||
var scale = new maplibregl.ScaleControl({ unit: milesFirst() ? 'imperial' : 'metric', maxWidth: 110 });
|
||||
map.addControl(scale, 'bottom-left');
|
||||
document.addEventListener('olt:units', function () {
|
||||
scale.setUnit(milesFirst() ? 'imperial' : 'metric');
|
||||
});
|
||||
|
||||
/* A narrow frame has no room for the open attribution beside the scale
|
||||
bar; keep it behind its button there, resizing included. */
|
||||
function collapseAttribution() {
|
||||
if (host.clientWidth >= 560) return;
|
||||
host.querySelectorAll('.maplibregl-ctrl-attrib').forEach(function (el) {
|
||||
el.classList.remove('maplibregl-compact-show');
|
||||
el.removeAttribute('open');
|
||||
});
|
||||
}
|
||||
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'); });
|
||||
|
||||
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);
|
||||
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;
|
||||
host.dataset.state = 'ready';
|
||||
status.textContent = '';
|
||||
collapseAttribution();
|
||||
if (entry.visibleIds) setVisible(entry, entry.visibleIds);
|
||||
if (kind === 'overview') wireOverview(map, defs);
|
||||
mapCorners();
|
||||
});
|
||||
|
||||
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);
|
||||
defs.forEach(function (def) { map.setPaintProperty(def.id, 'line-color', token(def.color)); });
|
||||
});
|
||||
}
|
||||
|
||||
mapStarters.push(function () {
|
||||
if (entry.mapStarted) return;
|
||||
entry.mapStarted = true;
|
||||
startMapLibre();
|
||||
});
|
||||
}
|
||||
|
||||
function startMaps() {
|
||||
mapStarters.forEach(function (start) { start(); });
|
||||
}
|
||||
|
||||
function entryFor(id) {
|
||||
return document.querySelector('.entry[data-id="' + (window.CSS && CSS.escape ? CSS.escape(id) : id) + '"]');
|
||||
}
|
||||
|
||||
function highlight(id) {
|
||||
maps.forEach(function (m) {
|
||||
if (m.map && m.ready && m.map.getLayer('olt-hi')) m.map.setFilter('olt-hi', ['==', ['get', 'id'], id || '']);
|
||||
});
|
||||
document.querySelectorAll('.entry.is-highlit').forEach(function (li) { li.classList.remove('is-highlit'); });
|
||||
if (id) {
|
||||
var li = entryFor(id);
|
||||
if (li) li.classList.add('is-highlit');
|
||||
}
|
||||
}
|
||||
|
||||
function wireOverview(map, defs) {
|
||||
var popup = new maplibregl.Popup({ closeButton: true, maxWidth: '18rem' });
|
||||
defs.filter(function (d) { return d.hit; }).forEach(function (def) {
|
||||
map.on('mousemove', def.id, function (e) {
|
||||
map.getCanvas().style.cursor = 'pointer';
|
||||
highlight(e.features[0].properties.id);
|
||||
});
|
||||
map.on('mouseleave', def.id, function () {
|
||||
map.getCanvas().style.cursor = '';
|
||||
highlight('');
|
||||
});
|
||||
map.on('click', def.id, function (e) {
|
||||
var p = e.features[0].properties;
|
||||
var box = document.createElement('div');
|
||||
var a = document.createElement('a');
|
||||
a.href = '/trails/' + encodeURIComponent(p.id) + '/';
|
||||
a.textContent = p.name;
|
||||
var meta = document.createElement('p');
|
||||
meta.textContent = lengthText(Number(p.length_km)) + (p.kind === 'route' ? ' · person-defined route' : '');
|
||||
box.appendChild(a);
|
||||
box.appendChild(meta);
|
||||
popup.setLngLat(e.lngLat).setDOMContent(box).addTo(map);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* Fit the overview map to the lines still shown; when every line is shown
|
||||
again that is the full extent the map opened at. */
|
||||
function fitToVisible(entry, ids) {
|
||||
var map = entry.map;
|
||||
if (!map || !entry.ready || entry.kind !== 'overview' || !entry.boundsById) return;
|
||||
var union = null;
|
||||
var shown = 0;
|
||||
var total = Object.keys(entry.boundsById).length;
|
||||
ids.forEach(function (id) {
|
||||
var b = entry.boundsById[id];
|
||||
if (!b) return;
|
||||
shown += 1;
|
||||
union = union
|
||||
? [Math.min(union[0], b[0]), Math.min(union[1], b[1]), Math.max(union[2], b[2]), Math.max(union[3], b[3])]
|
||||
: b.slice();
|
||||
});
|
||||
if (!union) return;
|
||||
var target = shown >= total && entry.fullBounds ? entry.fullBounds : union;
|
||||
var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
map.fitBounds([[target[0], target[1]], [target[2], target[3]]],
|
||||
{ padding: 32, maxZoom: 11, animate: !reduceMotion });
|
||||
}
|
||||
|
||||
function setVisible(entry, ids) {
|
||||
entry.visibleIds = ids;
|
||||
var set = {};
|
||||
ids.forEach(function (id) { set[id] = true; });
|
||||
entry.fallback.querySelectorAll('[data-id]').forEach(function (path) {
|
||||
path.style.display = set[path.getAttribute('data-id')] ? '' : 'none';
|
||||
});
|
||||
var map = entry.map;
|
||||
if (!map || !entry.ready) return;
|
||||
var inSet = ['in', ['get', 'id'], ['literal', ids]];
|
||||
entry.defs.forEach(function (def) {
|
||||
if (def.id === 'olt-hi') return;
|
||||
map.setFilter(def.id, def.filter ? ['all', def.filter, inSet] : inSet);
|
||||
});
|
||||
fitToVisible(entry, ids);
|
||||
}
|
||||
|
||||
/* Fetch the line data and draw the fallback at once; start MapLibre now if
|
||||
it is already here, and otherwise when the page has loaded (the deferred
|
||||
MapLibre script follows this one). The finder and the other controls
|
||||
below never wait for it. */
|
||||
document.querySelectorAll('.mapfig[data-map]').forEach(initMap);
|
||||
if (window.maplibregl || document.readyState === 'complete') startMaps();
|
||||
else window.addEventListener('load', startMaps);
|
||||
|
||||
/* 3. Trail finder (home page) ------------------------------------------------ */
|
||||
|
||||
function initFinder(form) {
|
||||
var list = document.getElementById('entries');
|
||||
var items = Array.prototype.slice.call(list.querySelectorAll('.entry'));
|
||||
var count = document.getElementById('results-count');
|
||||
var empty = document.getElementById('empty-state');
|
||||
var active = form.querySelector('.filters__active');
|
||||
var lenHint = document.getElementById('len-hint');
|
||||
var listHead = document.querySelector('.list-head');
|
||||
var el = form.elements;
|
||||
var sort = document.getElementById('sort');
|
||||
var more = form.querySelector('.filters__more');
|
||||
var total = items.length;
|
||||
|
||||
/* The count is the one live region. Keep it quiet through the first
|
||||
application below so nothing is announced on load, and write to it
|
||||
only when its text changes. The length hint is a description of the
|
||||
length fields, not a live region of its own. */
|
||||
if (count) count.setAttribute('aria-live', 'off');
|
||||
if (lenHint) {
|
||||
lenHint.removeAttribute('aria-live');
|
||||
lenHint.removeAttribute('role');
|
||||
[el.min, el.max].forEach(function (field) {
|
||||
if (!field) return;
|
||||
var described = (field.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean);
|
||||
if (described.indexOf('len-hint') === -1) described.push('len-hint');
|
||||
field.setAttribute('aria-describedby', described.join(' '));
|
||||
});
|
||||
}
|
||||
|
||||
function setText(node, text) {
|
||||
if (node && node.textContent !== text) node.textContent = text;
|
||||
}
|
||||
|
||||
function hasOption(select, value) {
|
||||
return Array.prototype.some.call(select.options, function (o) { return o.value === value; });
|
||||
}
|
||||
|
||||
function read() {
|
||||
var min = Number(el.min.value) || 0;
|
||||
var max = Number(el.max.value) || Infinity;
|
||||
var swapped = min > max;
|
||||
if (swapped) { var keep = min; min = max; max = keep; }
|
||||
return {
|
||||
q: el.q.value.trim(),
|
||||
words: el.q.value.trim().toLowerCase().split(/\s+/).filter(Boolean),
|
||||
country: el.country.value,
|
||||
region: el.region.value,
|
||||
min: min,
|
||||
max: max,
|
||||
swapped: swapped,
|
||||
designated: el.designated.checked,
|
||||
route: el.route.checked,
|
||||
line: el.line.checked,
|
||||
policy: el.policy.value,
|
||||
tier: el.tier.value
|
||||
};
|
||||
}
|
||||
|
||||
function matches(li, s) {
|
||||
var d = li.dataset;
|
||||
if (s.words.some(function (w) { return d.search.indexOf(w) === -1; })) return false;
|
||||
if (s.country !== 'all') {
|
||||
var countries = (d.countries || d.country || '').split(/\s+/).filter(Boolean);
|
||||
if (countries.indexOf(s.country) === -1) return false;
|
||||
}
|
||||
if (s.region) {
|
||||
var regions = d.regions.split(' ');
|
||||
if (regions.indexOf(s.region) === -1 && regions.indexOf(s.region.slice(0, 2) + '-*') === -1) return false;
|
||||
}
|
||||
var km = Number(d.km);
|
||||
if (km < s.min || km > s.max) return false;
|
||||
if (d.kind === 'route' ? !s.route : !s.designated) return false;
|
||||
if (s.line && d.line !== 'yes') return false;
|
||||
if (s.policy && d.policy !== s.policy) return false;
|
||||
if (s.tier && d.tier !== s.tier) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function lengthLabel(km) {
|
||||
var k = fmt.format(km) + ' km';
|
||||
var m = fmt.format(Math.round(km / KM_PER_MI)) + ' mi';
|
||||
return milesFirst() ? m + ' · ' + k : k + ' · ' + m;
|
||||
}
|
||||
|
||||
function describeLength(s) {
|
||||
var text;
|
||||
if (!s.min && s.max === Infinity) text = 'Any length.';
|
||||
else if (!s.min) text = 'Up to ' + lengthText(s.max) + '.';
|
||||
else if (s.max === Infinity) text = 'From ' + lengthText(s.min) + ' up.';
|
||||
else text = 'From ' + lengthText(s.min) + ' to ' + lengthText(s.max) + '.';
|
||||
if (s.swapped) text += ' Shortest and longest were swapped.';
|
||||
return text;
|
||||
}
|
||||
|
||||
function relabelLengths() {
|
||||
form.querySelectorAll('select[data-length-options] option').forEach(function (o) {
|
||||
if (o.value) o.textContent = lengthLabel(Number(o.value));
|
||||
});
|
||||
setText(lenHint, describeLength(read()));
|
||||
}
|
||||
|
||||
/* URL query <-> form. Only values that differ from the defaults are written. */
|
||||
function toQuery(s) {
|
||||
var p = new URLSearchParams();
|
||||
if (s.q) p.set('q', s.q);
|
||||
if (s.country !== 'all') p.set('country', s.country);
|
||||
if (s.region) p.set('region', s.region);
|
||||
if (s.min) p.set('min', String(s.min));
|
||||
if (s.max !== Infinity) p.set('max', String(s.max));
|
||||
if (s.designated !== s.route) p.set('kind', s.designated ? 'designated' : 'route');
|
||||
else if (!s.designated) p.set('kind', 'none');
|
||||
if (s.line) p.set('line', '1');
|
||||
if (s.policy) p.set('policy', s.policy);
|
||||
if (s.tier) p.set('tier', s.tier);
|
||||
if (sort.value !== 'name') p.set('sort', sort.value);
|
||||
return p.toString();
|
||||
}
|
||||
|
||||
function fromQuery() {
|
||||
var p = new URLSearchParams(window.location.search);
|
||||
el.q.value = p.get('q') || '';
|
||||
var country = p.get('country');
|
||||
syncRadios('#finder-form input[name="country"]', country === 'US' || country === 'CA' ? country : 'all');
|
||||
['region', 'min', 'max', 'policy', 'tier'].forEach(function (name) {
|
||||
var v = p.get(name) || '';
|
||||
el[name].value = hasOption(el[name], v) ? v : '';
|
||||
});
|
||||
var kind = p.get('kind');
|
||||
el.designated.checked = kind !== 'route' && kind !== 'none';
|
||||
el.route.checked = kind !== 'designated' && kind !== 'none';
|
||||
el.line.checked = p.get('line') === '1';
|
||||
var s = p.get('sort') || 'name';
|
||||
sort.value = hasOption(sort, s) ? s : 'name';
|
||||
limitRegions();
|
||||
}
|
||||
|
||||
function limitRegions() {
|
||||
var c = el.country.value;
|
||||
el.region.querySelectorAll('optgroup').forEach(function (g) { g.disabled = c !== 'all' && g.dataset.country !== c; });
|
||||
if (el.region.value && c !== 'all' && el.region.value.slice(0, 2) !== c) el.region.value = '';
|
||||
}
|
||||
|
||||
function applySort() {
|
||||
var key = sort.value;
|
||||
items.slice().sort(function (a, b) {
|
||||
if (key === 'long') return Number(b.dataset.km) - Number(a.dataset.km);
|
||||
if (key === 'short') return Number(a.dataset.km) - Number(b.dataset.km);
|
||||
return a.dataset.name.localeCompare(b.dataset.name);
|
||||
}).forEach(function (li) { list.appendChild(li); });
|
||||
}
|
||||
|
||||
function apply(updateUrl) {
|
||||
var s = read();
|
||||
var shown = [];
|
||||
items.forEach(function (li) {
|
||||
var ok = matches(li, s);
|
||||
li.hidden = !ok;
|
||||
if (ok) shown.push(li.dataset.id);
|
||||
});
|
||||
if (count && count.textContent !== shown.length + ' of ' + total + ' records') {
|
||||
count.innerHTML = '';
|
||||
var strong = document.createElement('strong');
|
||||
strong.textContent = String(shown.length);
|
||||
count.appendChild(strong);
|
||||
count.appendChild(document.createTextNode(' of ' + total + ' records'));
|
||||
}
|
||||
empty.hidden = shown.length > 0;
|
||||
if (listHead) listHead.hidden = shown.length === 0;
|
||||
setText(lenHint, describeLength(s));
|
||||
|
||||
var n = (s.words.length ? 1 : 0) + (s.country !== 'all' ? 1 : 0) + (s.region ? 1 : 0) +
|
||||
(s.min ? 1 : 0) + (s.max !== Infinity ? 1 : 0) + (!s.designated ? 1 : 0) + (!s.route ? 1 : 0) +
|
||||
(s.line ? 1 : 0) + (s.policy ? 1 : 0) + (s.tier ? 1 : 0);
|
||||
active.textContent = n ? n + ' active' : '';
|
||||
|
||||
maps.forEach(function (m) { if (m.kind === 'overview') setVisible(m, shown); });
|
||||
if (updateUrl) {
|
||||
var q = toQuery(s);
|
||||
window.history.replaceState(null, '', (q ? '?' + q : window.location.pathname) + window.location.hash);
|
||||
}
|
||||
}
|
||||
|
||||
form.querySelectorAll('input[name="country"]').forEach(function (r) { r.addEventListener('change', limitRegions); });
|
||||
form.addEventListener('input', function () { apply(true); });
|
||||
form.addEventListener('change', function () { apply(true); });
|
||||
form.addEventListener('submit', function (e) { e.preventDefault(); });
|
||||
form.addEventListener('reset', function () {
|
||||
setTimeout(function () {
|
||||
el.region.querySelectorAll('optgroup').forEach(function (g) { g.disabled = false; });
|
||||
apply(true);
|
||||
}, 0);
|
||||
});
|
||||
document.querySelectorAll('[data-reset]').forEach(function (b) {
|
||||
b.addEventListener('click', function () { form.reset(); el.q.focus(); });
|
||||
});
|
||||
sort.addEventListener('change', function () { applySort(); apply(true); });
|
||||
document.addEventListener('olt:units', relabelLengths);
|
||||
|
||||
items.forEach(function (li) {
|
||||
li.addEventListener('mouseenter', function () { highlight(li.dataset.id); });
|
||||
li.addEventListener('mouseleave', function () { highlight(''); });
|
||||
li.addEventListener('focusin', function () { highlight(li.dataset.id); });
|
||||
li.addEventListener('focusout', function () { highlight(''); });
|
||||
});
|
||||
|
||||
fromQuery();
|
||||
relabelLengths();
|
||||
applySort();
|
||||
apply(false);
|
||||
/* The count can announce from here on; the first application is done. */
|
||||
setTimeout(function () { if (count) count.removeAttribute('aria-live'); }, 0);
|
||||
/* The folded filters arrive closed; open them only where the filters
|
||||
have their own column (the finder's wide layout), and leave them
|
||||
closed on narrow screens. */
|
||||
if (more && window.matchMedia('(min-width: 70rem)').matches) more.open = true;
|
||||
window.addEventListener('popstate', function () { fromQuery(); applySort(); apply(false); });
|
||||
}
|
||||
|
||||
var finder = document.getElementById('finder-form');
|
||||
if (finder) initFinder(finder);
|
||||
|
||||
/* 4. Copy a required credit ------------------------------------------------ */
|
||||
|
||||
document.querySelectorAll('[data-copy]').forEach(function (button) {
|
||||
var target = document.querySelector(button.dataset.copy);
|
||||
var done = document.querySelector(button.dataset.copyStatus);
|
||||
if (!target) return;
|
||||
button.hidden = false;
|
||||
button.addEventListener('click', function () {
|
||||
var text = target.textContent.trim();
|
||||
function ok() { if (done) done.textContent = 'Copied: ' + text; }
|
||||
function manual() {
|
||||
var range = document.createRange();
|
||||
range.selectNodeContents(target);
|
||||
var sel = window.getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
if (done) done.textContent = 'Selected. Press Ctrl+C or ⌘C to copy.';
|
||||
}
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(ok, manual);
|
||||
else manual();
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 520" preserveAspectRatio="xMidYMid slice" fill="none" stroke="#9b7650" stroke-opacity=".42" stroke-linejoin="round"><path stroke-width="1" d="M0 298Q31 293 42 289Q54 284 63 278Q72 272 90 258Q108 243 114 239Q120 235 129 232Q138 228 183 216Q228 205 273 197Q318 189 330 184Q342 180 348 175Q354 170 361 163Q367 155 385 126Q402 96 408 93Q414 89 426 87Q438 85 447 82Q456 79 468 72Q480 65 492 52Q504 40 517 20L529 0"/><path stroke-width="1" d="M975 520Q981 496 992 470Q1002 444 1005 434Q1008 424 1008 415Q1009 406 1008 403Q1008 400 1005 395Q1002 390 996 388Q990 385 984 385Q978 385 945 397Q912 409 903 411Q894 413 885 413Q876 413 870 412Q864 410 858 407Q852 404 840 390Q828 377 822 372Q816 368 810 365Q804 363 798 363Q792 362 784 363Q777 365 770 368Q763 371 759 374Q754 377 749 382Q744 388 738 398Q732 408 713 449Q694 490 683 505L673 520"/><path stroke-width="1" d="M1416 0Q1423 18 1428 39Q1432 60 1436 69L1440 79"/><path stroke-width="1" d="M0 328Q30 326 43 321Q57 317 67 310Q78 304 102 284Q126 265 135 259Q144 253 156 247Q168 240 180 236Q192 231 207 227Q222 223 237 222Q252 220 264 220Q276 220 294 223Q312 226 318 226Q324 226 333 225Q342 223 348 220Q354 217 364 210Q373 203 400 176Q427 149 454 128Q480 107 489 99Q498 90 510 74Q522 57 537 28L553 0"/><path stroke-width="1" d="M1104 520Q1099 502 1096 495Q1092 488 1086 481Q1080 475 1070 467Q1060 460 1055 454Q1051 448 1049 442Q1047 436 1043 409Q1038 383 1035 376Q1032 369 1027 364Q1021 359 1015 356Q1008 354 999 354Q990 354 981 356Q972 358 951 366Q930 374 921 377Q912 379 903 380Q894 380 888 378Q883 377 878 374Q874 371 863 358Q852 345 846 340Q840 335 831 331Q822 328 804 324Q786 320 780 317Q774 313 770 306Q766 299 763 281Q759 263 756 254Q753 245 750 239Q746 233 742 229Q738 226 732 222Q726 219 720 217Q714 215 681 210Q648 204 640 201Q632 197 619 189Q606 180 597 178Q588 176 582 177Q576 179 570 184Q564 190 561 196Q557 203 557 212Q556 221 560 229Q564 236 576 247Q587 257 591 263Q595 269 598 278Q601 287 606 308Q610 329 614 338Q617 347 621 351Q624 356 630 361Q636 365 642 367Q648 369 663 372Q678 375 684 377Q690 380 693 383Q696 385 698 390Q700 394 700 400Q700 406 699 415Q697 424 689 445Q681 466 672 481Q663 496 650 508L637 520"/><path stroke-width="1" d="M1348 0Q1380 6 1385 9Q1391 12 1394 15Q1397 18 1402 27Q1407 36 1414 61Q1422 86 1425 91Q1428 96 1434 102L1440 109"/><path stroke-width="1" d="M0 353Q30 350 45 343Q60 337 72 329Q84 321 117 295Q150 269 162 262Q174 255 186 250Q198 246 210 243Q222 240 234 240Q246 239 255 240Q264 241 285 247Q306 253 315 254Q324 254 333 252Q342 251 354 245Q366 239 378 230Q390 221 417 196Q444 170 471 151Q499 131 505 126Q512 120 520 107Q528 94 542 62Q555 30 563 15L570 0"/><path stroke-width="1" d="M1143 520Q1135 508 1126 486Q1116 465 1110 456Q1104 448 1091 433Q1078 418 1075 412Q1071 406 1062 383Q1052 359 1048 353Q1044 348 1040 344Q1036 341 1028 337Q1020 334 1011 333Q1002 332 990 333Q978 335 954 340Q930 344 924 344Q918 344 912 342Q906 341 902 338Q898 335 887 324Q876 313 870 309Q864 306 858 303Q852 301 834 297Q816 292 807 287Q798 283 793 276Q788 269 777 248Q767 227 758 219Q750 211 741 207Q732 203 708 197Q684 192 675 189Q666 186 657 181Q648 176 630 162Q612 149 606 146Q600 144 591 142Q582 140 573 141Q564 142 558 144Q552 147 546 151Q540 155 536 161Q532 167 528 176Q524 185 520 200Q516 215 515 227Q513 239 514 248Q515 257 518 263Q522 270 525 272Q528 275 543 283Q558 290 565 298Q572 305 576 314Q579 323 585 347Q590 371 595 380Q599 389 606 393Q612 397 630 402Q648 407 654 411Q660 416 662 423Q665 430 664 439Q663 448 659 457Q655 466 649 476Q642 485 633 493Q624 501 615 506Q606 511 597 514Q588 516 579 516Q570 516 564 514Q558 512 546 502Q534 492 528 491Q522 489 513 493Q504 496 498 501Q492 505 486 513L479 520"/><path stroke-width="1" d="M1262 0Q1296 13 1326 18Q1356 23 1365 27Q1374 30 1377 33Q1381 36 1385 42Q1389 48 1396 69Q1404 90 1408 99Q1413 108 1419 114Q1424 120 1432 125L1440 130"/><path stroke-width="1" d="M0 375Q30 369 45 362Q60 356 75 345Q90 335 120 311Q150 286 162 279Q174 272 183 268Q192 264 204 261Q216 258 225 258Q234 257 243 259Q252 260 276 268Q300 276 309 276Q318 277 330 276Q342 274 354 270Q366 266 375 261Q384 257 411 236Q438 215 444 211Q450 208 456 206Q462 204 465 205Q468 205 471 210Q474 215 473 227Q472 239 467 254Q463 269 451 299Q439 329 438 335Q437 341 438 347Q438 354 441 358Q444 361 450 361Q456 361 480 348Q504 336 510 334Q516 333 522 333Q528 333 534 337Q540 340 542 343Q544 347 546 353Q548 359 548 365Q548 371 546 380Q545 389 541 397Q536 406 531 412Q527 418 512 432Q498 445 489 455Q480 465 471 479Q462 492 454 506L447 520"/><path stroke-width="1" d="M1203 520Q1176 514 1171 511Q1166 508 1162 504Q1158 500 1155 495Q1151 490 1139 466Q1128 442 1110 420Q1092 398 1077 370Q1062 342 1059 338Q1056 334 1050 330Q1044 325 1038 322Q1032 320 1023 318Q1014 316 987 316Q960 316 951 315Q942 314 933 310Q924 306 912 297Q900 288 894 284Q888 281 879 278Q870 275 852 272Q834 268 828 266Q822 264 814 257Q806 251 793 233Q780 215 771 208Q762 200 752 196Q742Line truncated
|
||||
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><rect x="5" y="1" width="6" height="14" rx="1" fill="#b3261e"/></svg>
|
||||
|
After Width: | Height: | Size: 130 B |
@@ -0,0 +1,93 @@
|
||||
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2014 The Source Serif 4 Project Authors (https://github.com/adobe-fonts/source-serif)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,13 @@
|
||||
/* 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). */
|
||||
(function () {
|
||||
'use strict';
|
||||
var root = document.documentElement;
|
||||
root.classList.add('js');
|
||||
try {
|
||||
var theme = localStorage.getItem('lh-theme');
|
||||
var units = localStorage.getItem('lh-units');
|
||||
if (theme === 'light' || theme === 'dark') root.dataset.theme = theme;
|
||||
if (units === 'mi') root.dataset.units = 'mi';
|
||||
} catch (e) { /* storage blocked: defaults apply */ }
|
||||
})();
|
||||
@@ -0,0 +1,41 @@
|
||||
# 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.
|
||||
|
||||
## MapLibre GL JS
|
||||
|
||||
| File | Package | Version | Licence |
|
||||
| --- | --- | --- | --- |
|
||||
| `maplibre-gl/maplibre-gl.js`, `maplibre-gl/maplibre-gl.css` | maplibre-gl | 4.7.1 | BSD-3-Clause, `maplibre-gl/LICENSE.txt` |
|
||||
|
||||
Downloaded unchanged from `https://unpkg.com/maplibre-gl@4.7.1/dist/` on
|
||||
2026-11-10. SHA-256:
|
||||
|
||||
```text
|
||||
be9633c4d870e26fb37f1cfe5c5a77181667114003ea16207ac7850d8da8add1 maplibre-gl.js
|
||||
576b085fdd9487a65a19215328c1e086c07ce5bf6da09b666b3806d3d008dae9 maplibre-gl.css
|
||||
```
|
||||
|
||||
The standard build runs its worker from a `blob:` URL, which the site's
|
||||
Content-Security-Policy allows (`worker-src blob:`). The bundle's last line
|
||||
names a source map that is not vendored.
|
||||
|
||||
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.
|
||||
|
||||
## Web fonts (`../fonts/`)
|
||||
|
||||
Latin subset only, as served by Google Fonts on 2026-11-10. Characters outside
|
||||
it fall back to the system serif or sans. The `@font-face` rules are at the top
|
||||
of `../style.css`.
|
||||
|
||||
| File | Family | Weights | Licence |
|
||||
| --- | --- | --- | --- |
|
||||
| `source-serif-4-latin.woff2` | Source Serif 4, roman | variable 400-700 | SIL OFL 1.1, `OFL-source-serif-4.txt` |
|
||||
| `source-serif-4-italic-latin.woff2` | Source Serif 4, italic | variable 400-600 | SIL OFL 1.1, `OFL-source-serif-4.txt` |
|
||||
| `ibm-plex-sans-condensed-{400,500,600}-latin.woff2` | IBM Plex Sans Condensed | 400, 500, 600 | SIL OFL 1.1, `OFL-ibm-plex-sans-condensed.txt` |
|
||||
|
||||
Source Serif 4 is the weight-only variable font (no optical-size axis): 51 KB
|
||||
instead of 122 KB.
|
||||
@@ -0,0 +1,116 @@
|
||||
Copyright (c) 2023, MapLibre contributors
|
||||
|
||||
All rights reserved.
|
||||
|
||||
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 MapLibre GL JS 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 OWNER 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 mapbox-gl-js v1.13 and earlier
|
||||
|
||||
Version v1.13 of mapbox-gl-js and earlier are licensed under a BSD-3-Clause license
|
||||
|
||||
Copyright (c) 2020, Mapbox
|
||||
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 Mapbox GL JS 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 OWNER 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 glfx.js
|
||||
|
||||
Copyright (C) 2011 by Evan Wallace
|
||||
|
||||
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.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Contains a portion of d3-color https://github.com/d3/d3-color
|
||||
|
||||
Copyright 2010-2016 Mike Bostock
|
||||
All rights reserved.
|
||||
|
||||
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 author nor the names of 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 OWNER 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.
|
||||
@@ -0,0 +1 @@
|
||||
.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0 0 0/0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}.maplibregl-ctrl button:not(:disabled):hover{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewLine truncated
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* MapLibre GL JS
|
||||
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.1/LICENSE.txt
|
||||
*/
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
||||
typeof define === 'function' && define.amd ? define(factory) :
|
||||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory());
|
||||
})(this, (function () { 'use strict';
|
||||
|
||||
/* eslint-disable */
|
||||
|
||||
var maplibregl = {};
|
||||
var modules = {};
|
||||
function define(moduleName, _dependencies, moduleFactory) {
|
||||
modules[moduleName] = moduleFactory;
|
||||
|
||||
// to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls)
|
||||
if (moduleName !== 'index') {
|
||||
return;
|
||||
}
|
||||
|
||||
// we assume that when an index module is initializing then other modules are loaded already
|
||||
var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);'
|
||||
|
||||
var sharedModule = {};
|
||||
// the order of arguments of a module factory depends on rollup (it decides who is whose dependency)
|
||||
// to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls)
|
||||
// we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following
|
||||
modules.shared(sharedModule);
|
||||
modules.index(maplibregl, sharedModule);
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' })));
|
||||
}
|
||||
|
||||
return maplibregl;
|
||||
};
|
||||
|
||||
|
||||
|
||||
define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}"function"==typeof SuppressedError&&SuppressedError;var n=i;function i(t,e){this.x=t,this.y=e;}i.prototype={clone:function(){return new i(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},i.convert=function(t){return t instanceof i?t:Array.isArray(t)?new i(t[0],t[1]):t};var s=r(n),a=o;function o(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}o.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)<e)return r;var s=this.sampleCurveDerivativeX(r);if(Math.abs(s)<1e-6)break;r-=i/s;}var a=0,o=1;for(r=t,n=0;n<20&&(i=this.sampleCurveX(r),!(Math.abs(i-t)<e));n++)t>i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}};var l=r(a);let u,c;function h(){return null==u&&(u="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),u}function p(){if(null==c&&(c=!1,h())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r<t*t;r++){const n=4*r;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(r%t,Math.floor(r/t),1,1);}const r=e.getImageData(0,0,t,t).data;for(let e=0;e<t*t*4;e++)if(e%4!=3&&r[e]!==e){c=!0;break}}}return c||!1}function f(t,e,r,n){const i=new l(t,e,r,n);return t=>i.solve(t)}const d=f(.25,.1,.25,1);function y(t,e,r){return Math.min(r,Math.max(e,t))}function m(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function g(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let x=1;function v(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function b(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function w(t){return Array.isArray(t)?t.map(w):"object"==typeof t&&t?v(t,w):t}const _={};function A(t){_[t]||("undefined"!=typeof console&&console.warn(t),_[t]=!0);}function S(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function k(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let M=null;function I(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCLine truncated
|
||||
|
||||
define("worker",["./shared"],(function(e){"use strict";class t{constructor(e){this.keyCache={},e&&this.replace(e);}replace(e){this._layerConfigs={},this._layers={},this.update(e,[]);}update(t,o){for(const o of t){this._layerConfigs[o.id]=o;const t=this._layers[o.id]=e.aA(o);t._featureFilter=e.a7(t.filter),this.keyCache[o.id]&&delete this.keyCache[o.id];}for(const e of o)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const i=e.bk(Object.values(this._layerConfigs),this.keyCache);for(const e of i){const t=e.map((e=>this._layers[e.id])),o=t[0];if("none"===o.visibility)continue;const i=o.source||"";let s=this.familiesBySource[i];s||(s=this.familiesBySource[i]={});const r=o.sourceLayer||"_geojsonTileLayer";let n=s[r];n||(n=s[r]=[]),n.push(t);}}}class o{constructor(t){const o={},i=[];for(const e in t){const s=t[e],r=o[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const o={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};i.push(o),r[e]={rect:o,metrics:t.metrics};}}const{w:s,h:r}=e.p(i),n=new e.o({width:s||1,height:r||1});for(const i in t){const s=t[i];for(const t in s){const r=s[+t];if(!r||0===r.bitmap.width||0===r.bitmap.height)continue;const a=o[i][t].rect;e.o.copy(r.bitmap,n,{x:0,y:0},{x:a.x+1,y:a.y+1},r.bitmap);}}this.image=n,this.positions=o;}}e.bl("GlyphAtlas",o);class i{constructor(t){this.tileID=new e.S(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,i,r,n){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a5;const a=new e.bm(Object.keys(t.layers).sort()),l=new e.bn(this.tileID,this.promoteId);l.bucketLayerIDs=[];const c={},u={featureIndex:l,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:r},h=i.familiesBySource[this.source];for(const o in h){const i=t.layers[o];if(!i)continue;1===i.version&&e.w(`Vector tile source "${this.source}" layer "${o}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const n=a.encode(o),d=[];for(let e=0;e<i.length;e++){const t=i.feature(e),s=l.getId(t,o);d.push({feature:t,id:s,index:e,sourceLayerIndex:n});}for(const t of h[o]){const o=t[0];o.source!==this.source&&e.w(`layer.source = ${o.source} does not equal this.source = ${this.source}`),o.minzoom&&this.zoom<Math.floor(o.minzoom)||o.maxzoom&&this.zoom>=o.maxzoom||"none"!==o.visibility&&(s(t,this.zoom,r),(c[o.id]=o.createBucket({index:l.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:n,sourceID:this.source})).populate(d,u,this.tileID.canonical),l.bucketLayerIDs.push(t.map((e=>e.id))));}}const d=e.aF(u.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let f=Promise.resolve({});if(Object.keys(d).length){const e=new AbortController;this.inFlightDependencies.push(e),f=n.sendAsync({type:"GG",data:{stacks:d,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const g=Object.keys(u.iconDependencies);let p=Promise.resolve({});if(g.length){const e=new AbortController;this.inFlightDependencies.push(e),p=n.sendAsync({type:"GI",data:{icons:g,source:this.source,tileID:this.tileID,type:"icons"}},e);}const m=Object.keys(u.patternDependencies);let y=Promise.resolve({});if(m.length){const e=new AbortController;this.inFlightDependencies.push(e),y=n.sendAsync({type:"GI",data:{icons:m,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[v,w,x]=yield Promise.all([f,p,y]),b=new o(v),S=new e.bo(w,x);for(const t in c){const o=c[t];o instanceof e.a6?(s(o.layers,this.zoom,r),e.bp({bucket:o,glyphMap:v,glyphPositions:b.positions,imageMap:w,imagePositions:S.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical})):o.hasPattern&&(o instanceof e.bq||o instanceof e.br||o instanceof e.bs)&&(s(o.layers,this.zoom,r),o.addFeatures(u,this.tileID.canonical,S.patternPositions));}return this.status="done",{buckets:Object.values(c).filter((e=>!e.isEmpty())),featureIndex:l,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:b.image,imageAtlas:S,glyphMap:this.returnDependencies?v:null,iconMap:this.returnDependencies?w:null,glyphPositions:this.returnDependencies?b.positions:null}}))}}function s(t,o,i){const s=new e.z(o);for(const e of t)e.recalculate(s,i);}class r{constructor(e,t,o){this.actor=e,this.layerIndex=t,this.availableImages=o,this.fetching={},this.loading={},this.loaded={};}loadVeLine truncated
|
||||
|
||||
define("index",["exports","./shared"],(function(t,e){"use strict";var i="4.7.1";let a,s;const o={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:t=>new Promise(((i,a)=>{const s=requestAnimationFrame(i);t.signal.addEventListener("abort",(()=>{cancelAnimationFrame(s),a(e.c());}));})),getImageData(t,e=0){return this.getImageCanvasContext(t).getImageData(-e,-e,t.width+2*e,t.height+2*e)},getImageCanvasContext(t){const e=window.document.createElement("canvas"),i=e.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return e.width=t.width,e.height=t.height,i.drawImage(t,0,0,t.width,t.height),i},resolveURL:t=>(a||(a=document.createElement("a")),a.href=t,a.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==s&&(s=matchMedia("(prefers-reduced-motion: reduce)")),s.matches)}};class r{static testProp(t){if(!r.docStyle)return t[0];for(let e=0;e<t.length;e++)if(t[e]in r.docStyle)return t[e];return t[0]}static create(t,e,i){const a=window.document.createElement(t);return void 0!==e&&(a.className=e),i&&i.appendChild(a),a}static createNS(t,e){return window.document.createElementNS(t,e)}static disableDrag(){r.docStyle&&r.selectProp&&(r.userSelect=r.docStyle[r.selectProp],r.docStyle[r.selectProp]="none");}static enableDrag(){r.docStyle&&r.selectProp&&(r.docStyle[r.selectProp]=r.userSelect);}static setTransform(t,e){t.style[r.transformProp]=e;}static addEventListener(t,e,i,a={}){t.addEventListener(e,i,"passive"in a?a:a.capture);}static removeEventListener(t,e,i,a={}){t.removeEventListener(e,i,"passive"in a?a:a.capture);}static suppressClickInternal(t){t.preventDefault(),t.stopPropagation(),window.removeEventListener("click",r.suppressClickInternal,!0);}static suppressClick(){window.addEventListener("click",r.suppressClickInternal,!0),window.setTimeout((()=>{window.removeEventListener("click",r.suppressClickInternal,!0);}),0);}static getScale(t){const e=t.getBoundingClientRect();return {x:e.width/t.offsetWidth||1,y:e.height/t.offsetHeight||1,boundingClientRect:e}}static getPoint(t,i,a){const s=i.boundingClientRect;return new e.P((a.clientX-s.left)/i.x-t.clientLeft,(a.clientY-s.top)/i.y-t.clientTop)}static mousePos(t,e){const i=r.getScale(t);return r.getPoint(t,i,e)}static touchPos(t,e){const i=[],a=r.getScale(t);for(let s=0;s<e.length;s++)i.push(r.getPoint(t,a,e[s]));return i}static mouseButton(t){return t.button}static remove(t){t.parentNode&&t.parentNode.removeChild(t);}}r.docStyle="undefined"!=typeof window&&window.document&&window.document.documentElement.style,r.selectProp=r.testProp(["userSelect","MozUserSelect","WebkitUserSelect","msUserSelect"]),r.transformProp=r.testProp(["transform","WebkitTransform"]);const n={supported:!1,testSupport:function(t){!c&&h&&(u?d(t):l=t);}};let l,h,c=!1,u=!1;function d(t){const e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);try{if(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,h),t.isContextLost())return;n.supported=!0;}catch(t){}t.deleteTexture(e),c=!0;}var _;"undefined"!=typeof document&&(h=document.createElement("img"),h.onload=()=>{l&&d(l),l=null,u=!0;},h.onerror=()=>{c=!0,l=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(t){let i,a,s,o;t.resetRequestQueue=()=>{i=[],a=0,s=0,o={};},t.addThrottleControl=t=>{const e=s++;return o[e]=t,e},t.removeThrottleControl=t=>{delete o[t],l();},t.getImage=(t,a,s=!0)=>new Promise(((o,r)=>{n.supported&&(t.headers||(t.headers={}),t.headers.accept="image/webp,*/*"),e.e(t,{type:"image"}),i.push({abortController:a,requestParameters:t,supportImageRefresh:s,state:"queued",onError:t=>{r(t);},onSuccess:t=>{o(t);}}),l();}));const r=t=>e._(this,void 0,void 0,(function*(){t.state="running";const{requestParameters:i,supportImageRefresh:s,onError:o,onSuccess:r,abortController:n}=t,c=!1===s&&!e.i(self)&&!e.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((t,e)=>t&&"accept"===e),!0));a++;const u=c?h(i,n):e.m(i,n);try{const i=yield u;delete t.abortController,t.state="completed",i.data instanceof HTMLImageElement||e.b(i.data)?r(i):i.data&&r({data:yield(d=i.data,"function"==typeof createImageBitmap?e.d(d):e.f(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(e){delete t.abortController,o(e);}finally{a--,l();}var d;})),l=()=>{const t=(()=>{for(const t of Object.keys(o))if(o[t]())return !0;return !1})()?e.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:e.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let e=a;e<t&&i.length>0;e++){const t=i.shift();t.abortController.signal.aborted?e--:r(t);}},h=(t,i)=>new Promise(((a,s)=>{const o=new Image,r=t.url,n=t.credentials;n&&"include"===n?o.crossOrigin="use-credentials":(n&&"same-origin"===n||!e.s(r))&&(o.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{o.src="",s(e.c());})),o.fetchPriority="high",o.onload=()=>{o.onerror=o.onload=null,a(Line truncated
|
||||
|
||||
//
|
||||
// Our custom intro provides a specialized "define()" function, called by the
|
||||
// AMD modules below, that sets up the worker blob URL and then executes the
|
||||
// main module, storing its exported value as 'maplibregl'
|
||||
|
||||
|
||||
var maplibregl$1 = maplibregl;
|
||||
|
||||
return maplibregl$1;
|
||||
|
||||
}));
|
||||
//# sourceMappingURL=maplibre-gl.js.map
|
||||
@@ -0,0 +1,493 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the static site data: downloads, map geometry, overview, trails.json and the bulk archives.
|
||||
|
||||
Python 3 standard library only. Run from anywhere:
|
||||
python3 web/build.py [--out _site] [--only id,id,...] [--force]
|
||||
"""
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
from olt import geo, records # noqa: E402
|
||||
|
||||
GPX_TOL_M = 5.0
|
||||
MAP_TOL_M = 30.0
|
||||
OVERVIEW_TOL_M = 750.0
|
||||
# Source files whose change means every trail's output is stale.
|
||||
CODE_FILES = [os.path.join(HERE, "build.py"),
|
||||
os.path.join(HERE, "olt", "geo.py"),
|
||||
os.path.join(HERE, "olt", "records.py")]
|
||||
# Incremental-build cache, deliberately outside the publish directory.
|
||||
CACHE_DIR = os.path.join(HERE, ".cache")
|
||||
# Files copied verbatim into the root of the publish directory (_headers, ...).
|
||||
STATIC_DIR = os.path.join(HERE, "static")
|
||||
|
||||
|
||||
class Stats:
|
||||
def __init__(self):
|
||||
self.processed = 0
|
||||
self.skipped_trails = 0
|
||||
self.written = 0
|
||||
self.skipped = 0
|
||||
|
||||
|
||||
def write_text(path, text, stats):
|
||||
with open(path, "w", encoding="utf-8", newline="") as f:
|
||||
f.write(text)
|
||||
stats.written += 1
|
||||
|
||||
|
||||
def write_json(path, obj, stats, indent=None):
|
||||
write_text(path, json.dumps(obj, ensure_ascii=False, separators=(",", ":"),
|
||||
indent=indent) + "\n", stats)
|
||||
|
||||
|
||||
def copy_file(src, dst, stats):
|
||||
shutil.copyfile(src, dst)
|
||||
stats.written += 1
|
||||
|
||||
|
||||
def copy_static(static_dir, out_dir, stats):
|
||||
"""Copy everything under static_dir verbatim into out_dir.
|
||||
|
||||
The directory tree is preserved; static_dir itself may be missing.
|
||||
"""
|
||||
if not os.path.isdir(static_dir):
|
||||
return
|
||||
for base, _, names in os.walk(static_dir):
|
||||
rel = os.path.relpath(base, static_dir)
|
||||
target = out_dir if rel == "." else os.path.join(out_dir, rel)
|
||||
os.makedirs(target, exist_ok=True)
|
||||
for name in sorted(names):
|
||||
copy_file(os.path.join(base, name), os.path.join(target, name), stats)
|
||||
|
||||
|
||||
def mtime(path):
|
||||
return os.path.getmtime(path)
|
||||
|
||||
|
||||
def dir_mtime(path):
|
||||
"""Newest mtime of the files directly inside a directory."""
|
||||
return max(mtime(os.path.join(path, n)) for n in os.listdir(path)
|
||||
if os.path.isfile(os.path.join(path, n)))
|
||||
|
||||
|
||||
def warn(message):
|
||||
print(f"warning: {message}", file=sys.stderr)
|
||||
|
||||
|
||||
def multiline_feature(parts, props):
|
||||
return {"type": "Feature", "properties": props,
|
||||
"geometry": {"type": "MultiLineString", "coordinates": parts}}
|
||||
|
||||
|
||||
def trail_outputs(tid, files):
|
||||
"""Names of the data files written into _site/trails/<id>/ for these files."""
|
||||
names = []
|
||||
if "line" in files:
|
||||
names += [f"{tid}.geojson", f"{tid}.gpx"]
|
||||
if "alternates" in files:
|
||||
names += [f"{tid}-alternates.geojson", f"{tid}-alternates.gpx"]
|
||||
for src in files.get("extracts", {}):
|
||||
names.append(f"{tid}-{src}.geojson")
|
||||
if "line" in files or "alternates" in files:
|
||||
names.append("map.json")
|
||||
if "shield" in files:
|
||||
names.append(os.path.basename(files["shield"]))
|
||||
return names
|
||||
|
||||
|
||||
def is_data_file(name):
|
||||
"""Files this script owns in a trail's output directory (the pages step's
|
||||
index.html, trail.toml and release.txt are not among them)."""
|
||||
return name == "map.json" or name.endswith((".geojson", ".gpx")) or name in records.SHIELD_NAMES
|
||||
|
||||
|
||||
def remove_stale(tdir, expected):
|
||||
"""Delete data files in a trail's output directory that this build does not produce."""
|
||||
for name in os.listdir(tdir):
|
||||
path = os.path.join(tdir, name)
|
||||
if name not in expected and is_data_file(name) and os.path.isfile(path):
|
||||
os.remove(path)
|
||||
|
||||
|
||||
def read_cache(cache_path):
|
||||
try:
|
||||
with open(cache_path, encoding="utf-8") as f:
|
||||
cache = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return cache if isinstance(cache, dict) else None
|
||||
|
||||
|
||||
def up_to_date(rec, files, tdir, cache_path, code_mtime):
|
||||
"""True when the outputs are complete, newer than the sources, and the cache
|
||||
records exactly the set of outputs this record now calls for."""
|
||||
names = trail_outputs(rec["id"], files)
|
||||
cache = read_cache(cache_path)
|
||||
if cache is None or cache.get("outputs") != sorted(names):
|
||||
return False
|
||||
if cache.get("creator") != gpx_creator(): # the site was renamed: the GPX creator is stale
|
||||
return False
|
||||
if "line" in files and "bbox" not in cache:
|
||||
return False
|
||||
paths = [os.path.join(tdir, n) for n in names] + [cache_path]
|
||||
if not all(os.path.isfile(p) for p in paths):
|
||||
return False
|
||||
newest_in = max(code_mtime, dir_mtime(os.path.join(ROOT, rec["id"])))
|
||||
return all(mtime(p) >= newest_in for p in paths)
|
||||
|
||||
|
||||
def download(tdir, name, role, note, fmt):
|
||||
return {"file": name, "format": fmt, "role": role,
|
||||
"bytes": os.path.getsize(os.path.join(tdir, name)), "note": note}
|
||||
|
||||
|
||||
def build_set(tid, key, path, stem, gpx_name, tdir, gpx_args, stats):
|
||||
"""Write one line file's outputs. Returns (parts, map parts), or None when
|
||||
the file has no line (or nothing is left of it after rounding)."""
|
||||
parts = geo.read_parts(path)
|
||||
simple = geo.round_coords(geo.simplify(parts, GPX_TOL_M), 6)
|
||||
small = geo.round_coords(geo.simplify(parts, MAP_TOL_M), 5)
|
||||
if not parts or not simple or not small:
|
||||
warn(f"{tid}: the {key} file {os.path.relpath(path, ROOT)} has no line; "
|
||||
f"treated as having no {key}")
|
||||
return None
|
||||
copy_file(path, os.path.join(tdir, f"{stem}.geojson"), stats)
|
||||
write_text(os.path.join(tdir, f"{stem}.gpx"),
|
||||
geo.gpx_text(simple, gpx_name, **gpx_args), stats)
|
||||
return parts, small
|
||||
|
||||
|
||||
def build_trail(rec, out_dir, code_mtime, force, stats):
|
||||
"""Write one trail's files. Returns (downloads, cache). The record's
|
||||
derived.files is replaced by the files that actually produced output."""
|
||||
tid = rec["id"]
|
||||
files = dict(rec["derived"]["files"])
|
||||
src = rec.get("source", {})
|
||||
tdir = os.path.join(out_dir, "trails", tid)
|
||||
cache_path = os.path.join(CACHE_DIR, f"{tid}.json")
|
||||
os.makedirs(tdir, exist_ok=True)
|
||||
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
||||
if rec["derived"]["has_line"] and "line" not in files:
|
||||
warn(f"{tid}: the record names a line file ({src.get('line_file')}) "
|
||||
f"but it is missing; treated as having no line")
|
||||
names = trail_outputs(tid, files)
|
||||
cache = {}
|
||||
|
||||
if not names:
|
||||
pass # record only: nothing to write
|
||||
elif not force and up_to_date(rec, files, tdir, cache_path, code_mtime):
|
||||
stats.skipped_trails += 1
|
||||
stats.skipped += len(names)
|
||||
cache = read_cache(cache_path)
|
||||
else:
|
||||
stats.processed += 1
|
||||
gpx_args = dict(url=src.get("url", ""), attribution=src.get("attribution", ""),
|
||||
licence=src.get("licence", ""), licence_text=src.get("licence_text", ""),
|
||||
creator=gpx_creator())
|
||||
maps = []
|
||||
if "line" in files:
|
||||
built = build_set(tid, "line", os.path.join(ROOT, files["line"]), tid,
|
||||
rec["name"], tdir, gpx_args, stats)
|
||||
if built is None:
|
||||
del files["line"]
|
||||
else:
|
||||
parts, small = built
|
||||
maps.append(multiline_feature(small, {"role": "main"}))
|
||||
cache = {"bbox": geo.bbox(parts), "points": geo.point_count(parts),
|
||||
"elevation": geo.has_elevation(parts)}
|
||||
if "alternates" in files:
|
||||
built = build_set(tid, "alternates", os.path.join(ROOT, files["alternates"]),
|
||||
f"{tid}-alternates", rec["name"] + " (alternates)",
|
||||
tdir, gpx_args, stats)
|
||||
if built is None:
|
||||
del files["alternates"]
|
||||
else:
|
||||
maps.append(multiline_feature(built[1], {"role": "alternate"}))
|
||||
for source, rel in files.get("extracts", {}).items():
|
||||
copy_file(os.path.join(ROOT, rel), os.path.join(tdir, f"{tid}-{source}.geojson"), stats)
|
||||
if maps:
|
||||
# The bbox covers the coordinates as published (rounded), not the source's.
|
||||
box = geo.merge_bbox([geo.bbox(m["geometry"]["coordinates"]) for m in maps])
|
||||
fc = {"type": "FeatureCollection", "bbox": box, "features": maps}
|
||||
write_json(os.path.join(tdir, "map.json"), fc, stats)
|
||||
if "shield" in files:
|
||||
name = os.path.basename(files["shield"])
|
||||
copy_file(os.path.join(ROOT, files["shield"]), os.path.join(tdir, name), stats)
|
||||
names = trail_outputs(tid, files)
|
||||
cache = dict(cache, outputs=sorted(names), creator=gpx_creator())
|
||||
if names:
|
||||
with open(cache_path, "w", encoding="utf-8") as f:
|
||||
json.dump(cache, f)
|
||||
|
||||
# Drop what an earlier build wrote and this one no longer produces.
|
||||
remove_stale(tdir, set(names))
|
||||
if not names or "line" not in files:
|
||||
cache = {k: v for k, v in (cache or {}).items() if k not in ("bbox", "points", "elevation")}
|
||||
if not names and os.path.isfile(cache_path):
|
||||
os.remove(cache_path)
|
||||
rec["derived"]["files"] = files
|
||||
|
||||
# download list (from the files now on disk)
|
||||
downloads = []
|
||||
if "line" in files:
|
||||
downloads.append(download(tdir, f"{tid}.geojson", "main",
|
||||
"Full resolution, as published in this dataset", "GeoJSON"))
|
||||
downloads.append(download(tdir, f"{tid}.gpx", "main",
|
||||
"Simplified to 5 m, 6 decimals", "GPX"))
|
||||
if "alternates" in files:
|
||||
downloads.append(download(tdir, f"{tid}-alternates.geojson", "alternates",
|
||||
"Alternate and connector lines, full resolution", "GeoJSON"))
|
||||
downloads.append(download(tdir, f"{tid}-alternates.gpx", "alternates",
|
||||
"Alternate and connector lines, simplified to 5 m", "GPX"))
|
||||
for source in files.get("extracts", {}):
|
||||
downloads.append(download(tdir, f"{tid}-{source}.geojson", "extract",
|
||||
f"Line as served by source '{source}', full resolution", "GeoJSON"))
|
||||
return downloads, cache or {}
|
||||
|
||||
|
||||
def read_main_map_parts(tdir):
|
||||
try:
|
||||
with open(os.path.join(tdir, "map.json"), encoding="utf-8") as f:
|
||||
fc = json.load(f)
|
||||
except OSError:
|
||||
return []
|
||||
for feat in fc["features"]:
|
||||
if feat["properties"].get("role") == "main":
|
||||
return feat["geometry"]["coordinates"]
|
||||
return []
|
||||
|
||||
|
||||
def overview_geojson(recs, out_dir):
|
||||
"""One MultiLineString per included trail, simplified from the 30 m map line."""
|
||||
features = []
|
||||
for rec in recs:
|
||||
if "line" not in rec["derived"]["files"]:
|
||||
continue
|
||||
parts = read_main_map_parts(os.path.join(out_dir, "trails", rec["id"]))
|
||||
parts = geo.join_parts(parts) # many trails are thousands of short parts
|
||||
parts = geo.round_coords(geo.simplify(parts, OVERVIEW_TOL_M), 4)
|
||||
if not parts:
|
||||
continue
|
||||
props = {"id": rec["id"], "name": rec["name"], "kind": rec["derived"]["kind"],
|
||||
"country": rec["country"], "length_km": rec["length_km"]}
|
||||
features.append(multiline_feature(parts, props))
|
||||
return {"type": "FeatureCollection", "features": features}
|
||||
|
||||
|
||||
def prune_removed_trails(out_dir, ids):
|
||||
"""Remove trails/<id>/ output (and cache entries) for ids no longer in the dataset."""
|
||||
trails = os.path.join(out_dir, "trails")
|
||||
if os.path.isdir(trails):
|
||||
for name in os.listdir(trails):
|
||||
path = os.path.join(trails, name)
|
||||
if os.path.isdir(path) and name not in ids:
|
||||
shutil.rmtree(path)
|
||||
if os.path.isdir(CACHE_DIR):
|
||||
for name in os.listdir(CACHE_DIR):
|
||||
if name.endswith(".json") and name[:-5] not in ids:
|
||||
os.remove(os.path.join(CACHE_DIR, name))
|
||||
|
||||
|
||||
# Bulk archives under /data/: name -> (file extension inside, what the README calls them).
|
||||
ARCHIVES = {
|
||||
"all-gpx.zip": (".gpx", "GPX"),
|
||||
"all-geojson.zip": (".geojson", "GeoJSON"),
|
||||
}
|
||||
# Files at the top of every archive, from the repository root (left out when missing).
|
||||
ARCHIVE_DOCS = ("trails.csv", "SOURCES.md")
|
||||
|
||||
|
||||
def archive_members(name, recs, out_dir, root):
|
||||
"""[(name inside the archive, source path)] for one bulk archive, in a stable order:
|
||||
each trail's line files and release.txt as <id>/<file>, then trails.csv and SOURCES.md."""
|
||||
ext = ARCHIVES[name][0]
|
||||
members = []
|
||||
for rec in recs:
|
||||
tid = rec["id"]
|
||||
files = rec["derived"]["files"]
|
||||
stems = ([tid] if "line" in files else []) + ([f"{tid}-alternates"] if "alternates" in files else [])
|
||||
for stem in stems:
|
||||
members.append((f"{tid}/{stem}{ext}", os.path.join(out_dir, "trails", tid, stem + ext)))
|
||||
release = os.path.join(root, tid, "release.txt")
|
||||
if os.path.isfile(release):
|
||||
members.append((f"{tid}/release.txt", release))
|
||||
for doc in ARCHIVE_DOCS:
|
||||
path = os.path.join(root, doc)
|
||||
if os.path.isfile(path):
|
||||
members.append((doc, path))
|
||||
return members
|
||||
|
||||
|
||||
def archive_readme(name):
|
||||
ext, kind = ARCHIVES[name]
|
||||
if ext == ".gpx":
|
||||
what = "simplified to 5 m"
|
||||
resolution = ("The GPX files are simplified to 5 m, with coordinates to 6 decimal places.\n"
|
||||
"The full-resolution lines are in all-geojson.zip.\n")
|
||||
else:
|
||||
what = "full resolution"
|
||||
resolution = ("The GeoJSON files are the full-resolution lines, as published in this dataset.\n"
|
||||
"The simplified GPX files (5 m) are in all-gpx.zip.\n")
|
||||
rows = [(f"<id>/<id>{ext}", f"the main line, {what}"),
|
||||
(f"<id>/<id>-alternates{ext}", f"alternate and connector lines, {what}, where the\n"
|
||||
"source serves them separately"),
|
||||
("<id>/release.txt", "the source, licence and date the line files came from")]
|
||||
width = max(len(p) for p, _ in rows) + 3
|
||||
files = ""
|
||||
for path, what_it_is in rows:
|
||||
files += " " + path.ljust(width) + what_it_is.replace("\n", "\n" + " " * (width + 2)) + "\n"
|
||||
return (f"{site_name() or 'Long trails'}: every {kind} line\n\n"
|
||||
"For each trail or route whose record includes a line:\n\n"
|
||||
f"{files}\n"
|
||||
"and at the top:\n\n"
|
||||
" trails.csv one row per record, with its licence\n"
|
||||
" SOURCES.md each source, its terms, and the trails that use it\n\n"
|
||||
"Terms. Each line keeps its source's terms and needs its source's credit, as\n"
|
||||
"given in its <id>/release.txt (the Licence and Attribution lines) and in\n"
|
||||
"trails.csv (the licence column). Lines from OpenStreetMap are\n"
|
||||
"© OpenStreetMap contributors, under the ODbL. The records themselves are\n"
|
||||
"public domain (CC0-1.0).\n\n"
|
||||
f"{resolution}")
|
||||
|
||||
|
||||
def build_archive(name, recs, out_dir, stats):
|
||||
"""Write /data/<name> (zip, deflate) unless it already holds exactly these files
|
||||
and is newer than every one of them and than this script."""
|
||||
path = os.path.join(out_dir, "data", name)
|
||||
members = archive_members(name, recs, out_dir, ROOT)
|
||||
members = [(arc, src) for arc, src in members if os.path.isfile(src)]
|
||||
expected = ["README.txt"] + [arc for arc, _ in members]
|
||||
newest = max([mtime(__file__)] + [mtime(src) for _, src in members])
|
||||
if os.path.isfile(path) and mtime(path) >= newest:
|
||||
try:
|
||||
with zipfile.ZipFile(path) as zf:
|
||||
if zf.namelist() == expected:
|
||||
stats.skipped += 1
|
||||
return
|
||||
except (OSError, zipfile.BadZipFile):
|
||||
pass
|
||||
tmp = path + ".tmp" # written beside, then moved over: never a half-written archive
|
||||
try:
|
||||
with zipfile.ZipFile(tmp, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
info = zipfile.ZipInfo("README.txt", date_time=time.localtime(mtime(__file__))[:6])
|
||||
info.compress_type = zipfile.ZIP_DEFLATED
|
||||
info.external_attr = 0o644 << 16
|
||||
zf.writestr(info, archive_readme(name))
|
||||
for arc, src in members:
|
||||
zf.write(src, arc)
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
stats.written += 1
|
||||
|
||||
|
||||
def import_pages():
|
||||
try:
|
||||
from olt import pages
|
||||
except ImportError:
|
||||
return None
|
||||
return pages
|
||||
|
||||
|
||||
def gpx_creator():
|
||||
"""The creator attribute of every GPX file: the site's name."""
|
||||
return site_name() or "long-trails dataset"
|
||||
|
||||
|
||||
def site_name():
|
||||
"""The site's name from web/site.toml, or "" when olt.site is absent or unreadable."""
|
||||
try:
|
||||
from olt import site
|
||||
return site.load().name
|
||||
except Exception: # module absent or settings unreadable
|
||||
return ""
|
||||
|
||||
|
||||
def describe_site():
|
||||
"""One-line description of what is built, from web/site.toml when olt.site exists."""
|
||||
name = site_name()
|
||||
return f"the {name} site" if name else "the static site"
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=f"Build the data and pages for {describe_site()}.")
|
||||
ap.add_argument("--out", default="_site", help="output directory (default _site)")
|
||||
ap.add_argument("--only", default="",
|
||||
help="comma-separated trail ids to rebuild; site-wide files still cover every trail")
|
||||
ap.add_argument("--force", action="store_true", help="rebuild everything")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
start = time.time()
|
||||
out_dir = os.path.abspath(args.out)
|
||||
recs = records.load_records(ROOT)
|
||||
only = {x for x in args.only.split(",") if x}
|
||||
unknown = only - {r["id"] for r in recs}
|
||||
if unknown:
|
||||
raise SystemExit(f"unknown trail id(s): {', '.join(sorted(unknown))}")
|
||||
|
||||
code_mtime = max(mtime(p) for p in CODE_FILES)
|
||||
stats = Stats()
|
||||
os.makedirs(os.path.join(out_dir, "data"), exist_ok=True)
|
||||
# Older builds kept the cache in the publish directory; it must never ship.
|
||||
legacy_cache = os.path.join(out_dir, ".cache")
|
||||
if os.path.isdir(legacy_cache):
|
||||
shutil.rmtree(legacy_cache)
|
||||
|
||||
# Every trail goes through build_trail so the site-wide files are complete.
|
||||
# --only forces a rebuild of the chosen trails; the rest are rebuilt only
|
||||
# when stale or missing from the cache.
|
||||
for rec in recs:
|
||||
force = args.force or rec["id"] in only
|
||||
downloads, cache = build_trail(rec, out_dir, code_mtime, force, stats)
|
||||
d = rec["derived"]
|
||||
d["downloads"] = downloads
|
||||
if cache.get("bbox"):
|
||||
box = cache["bbox"]
|
||||
d["bbox"] = box
|
||||
d["center"] = [round((box[0] + box[2]) / 2, 5), round((box[1] + box[3]) / 2, 5)]
|
||||
d["points"] = cache["points"]
|
||||
|
||||
if not only:
|
||||
prune_removed_trails(out_dir, {r["id"] for r in recs})
|
||||
|
||||
write_json(os.path.join(out_dir, "data", "overview.geojson"),
|
||||
overview_geojson(recs, out_dir), stats)
|
||||
write_json(os.path.join(out_dir, "data", "trails.json"), recs, stats)
|
||||
for name in ("trails.csv", "index.geojson"):
|
||||
copy_file(os.path.join(ROOT, name), os.path.join(out_dir, "data", name), stats)
|
||||
for name in ARCHIVES:
|
||||
build_archive(name, recs, out_dir, stats)
|
||||
|
||||
copy_static(STATIC_DIR, out_dir, stats)
|
||||
|
||||
pages = import_pages()
|
||||
if pages is None:
|
||||
print("pages step skipped: olt.pages not found")
|
||||
else:
|
||||
pages.render_site(recs, out_dir, ROOT)
|
||||
|
||||
total = 0
|
||||
for base, _, names in os.walk(out_dir):
|
||||
total += sum(os.path.getsize(os.path.join(base, n)) for n in names)
|
||||
print(f"trails processed {stats.processed}, up to date {stats.skipped_trails}; "
|
||||
f"files written {stats.written}, skipped {stats.skipped}; "
|
||||
f"output {total / 1e6:.1f} MB; {time.time() - start:.1f} s")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
"""Data layer and page generator for the long-trails static site."""
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Pieces shared by the home page and the trail pages: record summaries and small components."""
|
||||
import re
|
||||
|
||||
from . import words
|
||||
from .markup import Markup, esc
|
||||
|
||||
|
||||
def trail_path(rec):
|
||||
return f"/trails/{rec['id']}/"
|
||||
|
||||
|
||||
def kind(rec):
|
||||
return rec["derived"]["kind"]
|
||||
|
||||
|
||||
def is_route(rec):
|
||||
return kind(rec) == "route"
|
||||
|
||||
|
||||
def has_line(rec):
|
||||
return rec["derived"]["has_line"]
|
||||
|
||||
|
||||
# A line whose measured length is further than this from the published length
|
||||
# (either way, in percent) needs a length_gap_note (docs/schema.md).
|
||||
LENGTH_LIMIT = 15.0
|
||||
|
||||
|
||||
def line_differs(rec):
|
||||
"""True when the record has a line, the line was measured, and the measured
|
||||
length differs from the published length by more than 15%. The one test of
|
||||
a partial line used by every page."""
|
||||
v = rec.get("verification", {})
|
||||
diff = v.get("difference_percent")
|
||||
return bool(has_line(rec) and v.get("verified") and diff is not None
|
||||
and abs(diff) > LENGTH_LIMIT)
|
||||
|
||||
|
||||
def line_short(rec):
|
||||
"""line_differs, and the measured line is the shorter: the line is partial."""
|
||||
return line_differs(rec) and rec["verification"]["difference_percent"] < 0
|
||||
|
||||
|
||||
def partial_short_text(rec):
|
||||
"""The short form for lists: "Line measures 2.0 km of 1,100 km published"."""
|
||||
v = rec["verification"]
|
||||
word = "of" if v["difference_percent"] < 0 else "against"
|
||||
return (f"Line measures {words.fmt_km1(v['measured_km'])} km {word} "
|
||||
f"{words.fmt_km(rec['length_km'])} km published")
|
||||
|
||||
|
||||
def name(rec):
|
||||
"""The record's name as HTML text, marked with its language when it is not
|
||||
English (web/site.toml [name_lang], copied to derived.name_lang by pages.py).
|
||||
Every place a page shows a record's name as text goes through here."""
|
||||
lang = rec.get("derived", {}).get("name_lang", "")
|
||||
text = esc(rec["name"])
|
||||
return Markup(f'<span lang="{esc(lang)}">{text}</span>') if lang else text
|
||||
|
||||
|
||||
def countries(rec):
|
||||
"""Every country the record touches: its own, and the country of each of its regions.
|
||||
In "US", "CA" order."""
|
||||
found = {rec["country"]} | {words.region_country(c) for c in rec.get("regions", [])}
|
||||
return [c for c in ("US", "CA") if c in found] + sorted(found - {"US", "CA", ""})
|
||||
|
||||
|
||||
_OSM_CREDIT = re.compile(r"(?<!©)(?<!© )(?<!© )OpenStreetMap contributors")
|
||||
|
||||
|
||||
def credit_text(attribution):
|
||||
"""The credit to show and copy: the record's attribution verbatim, with
|
||||
"© " before "OpenStreetMap contributors" where it is not already there."""
|
||||
return _OSM_CREDIT.sub("© OpenStreetMap contributors", attribution or "")
|
||||
|
||||
|
||||
def sentence(text):
|
||||
"""Text ending in a full stop, without doubling one already there."""
|
||||
text = (text or "").rstrip()
|
||||
return text if not text or text.endswith((".", "!", "?")) else text + "."
|
||||
|
||||
|
||||
def policy(rec):
|
||||
return rec.get("route", {}).get("line_policy", "")
|
||||
|
||||
|
||||
def shield_url(rec):
|
||||
shield = rec["derived"]["files"].get("shield")
|
||||
return f"/trails/{rec['id']}/{shield.rsplit('/', 1)[-1]}" if shield else ""
|
||||
|
||||
|
||||
def designated_year(rec):
|
||||
""""National Scenic Trail (2009)" -> "2009"; "" when the designation has no year in brackets."""
|
||||
m = re.search(r"\((\d{4})\)", rec.get("designation", ""))
|
||||
return m.group(1) if m else ""
|
||||
|
||||
|
||||
def short_source(rec):
|
||||
"""A short name for where the included line came from, for lists."""
|
||||
src = rec.get("source", {})
|
||||
if src.get("osm_only"):
|
||||
name = "OpenStreetMap"
|
||||
else:
|
||||
name = re.split(r" \(|, | with ", src.get("line_source", ""))[0]
|
||||
if "OpenStreetMap" in src.get("attribution", "") and "OpenStreetMap" not in name:
|
||||
name += " and OpenStreetMap"
|
||||
return name
|
||||
|
||||
|
||||
def licence_label(rec):
|
||||
src = rec.get("source", {})
|
||||
text = words.label(words.LICENCES, src.get("licence", ""))
|
||||
if "ODbL" in src.get("attribution", "") and src.get("licence") != "ODbL-1.0":
|
||||
text += " and ODbL 1.0"
|
||||
return text
|
||||
|
||||
|
||||
def rich(text):
|
||||
"""Escape record text, setting `backticked` spans (Overpass queries and the like) as code."""
|
||||
parts = esc(text).split("`")
|
||||
if len(parts) % 2 == 0: # unbalanced backticks: leave the text as it is
|
||||
return esc(text)
|
||||
return Markup("".join(f"<code>{p}</code>" if i % 2 else p for i, p in enumerate(parts)))
|
||||
|
||||
|
||||
def absent_reason_short(rec):
|
||||
"""line_absent_reason without the opening "No line is included." (the status already says so)."""
|
||||
reason = rec.get("source", {}).get("line_absent_reason", "")
|
||||
return re.sub(r"^No line is included\.\s*", "", reason) or reason
|
||||
|
||||
|
||||
def regions_html(rec, linked=False):
|
||||
"""Region codes with their names; optionally each linked to the filtered list."""
|
||||
parts = []
|
||||
for code in rec.get("regions", []):
|
||||
name = words.region_name(code)
|
||||
if code == words.ALL_CANADA:
|
||||
text = Markup(esc(name))
|
||||
href = "/regions/#canada-wide"
|
||||
else:
|
||||
text = Markup(f'<abbr title="{esc(name)}">{esc(code)}</abbr>')
|
||||
href = f"/regions/{words.region_key(code, rec['country']).lower()}/"
|
||||
if linked:
|
||||
text = Markup(f'<a href="{esc(href)}">{text}</a>')
|
||||
parts.append(text)
|
||||
return Markup(" ".join(parts))
|
||||
|
||||
|
||||
def tags(rec, with_policy=True):
|
||||
"""Kind, tier and listing tags, and (with_policy) the line policy of a route."""
|
||||
out = []
|
||||
if is_route(rec):
|
||||
out.append('<span class="tag tag--route">Person-defined route</span>')
|
||||
elif rec.get("tier") == "national":
|
||||
out.append('<span class="tag tag--nst">National Scenic Trail</span>')
|
||||
else:
|
||||
out.append('<span class="tag">Designated trail</span>')
|
||||
tier = rec.get("tier")
|
||||
if tier in ("short", "deferred", "candidate"):
|
||||
out.append(f'<span class="tag tag--quiet">{esc(words.label(words.TIERS, tier))}</span>')
|
||||
if str(rec.get("wave")) == "held":
|
||||
out.append('<span class="tag tag--quiet">Held</span>')
|
||||
if is_route(rec) and with_policy:
|
||||
out.append(policy_chip(policy(rec)))
|
||||
return Markup("".join(out))
|
||||
|
||||
|
||||
def policy_chip(value):
|
||||
lab, short = words.label(words.POLICIES, value), words.meaning(words.POLICIES, value)
|
||||
return Markup(f'<span class="policy policy--{esc(value)}" title="Line policy: {esc(short)}">'
|
||||
f'<span class="vh">Line policy: </span>{esc(lab)}</span>')
|
||||
|
||||
|
||||
def logo_img(rec, alt, eager=False):
|
||||
"""The logo <img>: the PNG thumbnail at its real size when there is one (olt/thumbs.py), else the file."""
|
||||
logo = rec["derived"].get("logo_img")
|
||||
src, dims = (logo["src"], f' width="{logo["width"]}" height="{logo["height"]}"') if logo \
|
||||
else (shield_url(rec), "")
|
||||
loading = "" if eager else ' loading="lazy"'
|
||||
return f'<img src="{esc(src)}" alt="{esc(alt)}"{dims}{loading} decoding="async">'
|
||||
|
||||
|
||||
def plate(rec, *, size="", link=False, eager=False, alt=None):
|
||||
"""The logo on a light plate, or a dashed plate with the short name when there is no logo file.
|
||||
|
||||
link: the logo links to the full-size file. eager: not lazy-loaded (the record page header).
|
||||
alt: the image's text; by default "<name> logo" on a sized plate and "" on a list plate.
|
||||
A linked image with alt="" gets its link text from a visually hidden span instead.
|
||||
"""
|
||||
url = shield_url(rec)
|
||||
cls = f"plate plate--{size}" if size else "plate"
|
||||
if url:
|
||||
if alt is None:
|
||||
alt = f"{rec['name']} logo" if size else ""
|
||||
img = logo_img(rec, alt, eager)
|
||||
if link:
|
||||
label = "" if alt else f'<span class="vh">Full-size logo: {name(rec)}</span>'
|
||||
img = f'<a href="{esc(url)}">{img}{label}</a>'
|
||||
return Markup(f'<div class="{cls}">{img}</div>')
|
||||
return Markup(f'<div class="{cls} plate--none" aria-hidden="true"><span>{esc(rec.get("short_name", ""))}</span></div>')
|
||||
|
||||
|
||||
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>')
|
||||
SWATCH_NONE = Markup('<span class="swatch swatch--none" aria-hidden="true"></span>')
|
||||
|
||||
ICON_DOWNLOAD = Markup('<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">'
|
||||
'<path d="M8 1.5v9M4 7l4 4 4-4M2.5 14.5h11" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>')
|
||||
ICON_EXTERNAL = Markup('<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">'
|
||||
'<path d="M6 3H3v10h10v-3M9 2.5h4.5V7M13.5 2.5 7 9" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>')
|
||||
@@ -0,0 +1,405 @@
|
||||
"""Document-backed pages: /sources/, /logos/, /about/, /data/ and sub-pages.
|
||||
|
||||
Markdown goes through olt.md; relative links are rewritten to site pages.
|
||||
Repository paths with no site page become repository links when repo_url
|
||||
is set, and plain text otherwise (never a dead link).
|
||||
"""
|
||||
import collections
|
||||
import os
|
||||
import re
|
||||
|
||||
from . import common, md, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
REAL_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
def read_doc(repo_root, relpath):
|
||||
"""Read a repository document, falling back to this checkout's copy."""
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
path = os.path.join(base, *relpath.split("/"))
|
||||
if os.path.isfile(path):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
return ""
|
||||
|
||||
|
||||
_PAGE_MAP = {
|
||||
"docs/schema.md": "/data/schema/",
|
||||
"schema.md": "/data/schema/",
|
||||
"notice.md": "/logos/",
|
||||
"sources.md": "/sources/",
|
||||
"contributing.md": "/about/",
|
||||
"changelog.md": "/data/changelog/",
|
||||
"readme.md": "/about/",
|
||||
"license": "/licences/LICENSE",
|
||||
"trails.csv": "/data/trails.csv",
|
||||
"trails.json": "/data/trails.json",
|
||||
"index.geojson": "/data/index.geojson",
|
||||
"overview.geojson": "/data/overview.geojson",
|
||||
}
|
||||
|
||||
|
||||
def _classify(href, site):
|
||||
"""Site href for a Markdown destination, or None to drop the link."""
|
||||
if not href or href.startswith(("#", "/", "http://", "https://", "mailto:", "tel:")):
|
||||
return href
|
||||
path, _, frag = href.partition("#")
|
||||
norm = path[2:] if path.startswith("./") else path
|
||||
while norm.startswith("../"):
|
||||
norm = norm[3:]
|
||||
key = norm.lower()
|
||||
if key in _PAGE_MAP:
|
||||
return _PAGE_MAP[key] + (f"#{frag}" if frag else "")
|
||||
if key.startswith("licenses/") and key.endswith(".txt"):
|
||||
return "/licences/" + norm.split("/", 1)[1] + (f"#{frag}" if frag else "")
|
||||
if site.repo_url:
|
||||
return f"{site.repo_url}/blob/main/{norm}" + (f"#{frag}" if frag else "")
|
||||
return None
|
||||
|
||||
|
||||
def make_link_rewrite(site):
|
||||
"""md.render link_rewrite: the site href, or None (md.py then keeps the link's text only)."""
|
||||
return lambda href: _classify(href, site)
|
||||
|
||||
|
||||
def _link_text(html, phrase, url):
|
||||
"""Link each occurrence of phrase in the text of html (not inside a tag or an existing link)."""
|
||||
out, depth = [], 0
|
||||
for part in re.split(r"(<[^>]*>)", html):
|
||||
if part.startswith("<"):
|
||||
if re.match(r"<a[\s>]", part):
|
||||
depth += 1
|
||||
elif part.startswith("</a"):
|
||||
depth = max(0, depth - 1)
|
||||
elif depth == 0 and phrase in part:
|
||||
part = part.replace(phrase, f'<a href="{esc(url)}">{phrase}</a>')
|
||||
out.append(part)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def link_requests(html, site):
|
||||
"""Link the documents' own words asking readers to open an issue or to write
|
||||
to the maintainers, when site.toml says where (repo_url, contact_url).
|
||||
The wording is left as the documents have it; with neither set, nothing changes."""
|
||||
issue = site.issues_url or site.contact_url
|
||||
contact = site.contact_url or site.repo_url
|
||||
if issue:
|
||||
for phrase in ("Open an issue", "open an issue", "opening an issue"):
|
||||
html = _link_text(html, phrase, issue)
|
||||
if contact:
|
||||
for phrase in ("writing to the repository maintainers", "write to the repository maintainers"):
|
||||
html = _link_text(html, phrase, contact)
|
||||
return Markup(html)
|
||||
|
||||
|
||||
def render_doc(text, site, *, heading_offset=0, drop_h1=False):
|
||||
"""Render Markdown to HTML with rewritten links and scrollable tables."""
|
||||
if drop_h1:
|
||||
text = re.sub(r"\A# [^\n]*\n+", "", text, count=1)
|
||||
html = md.render(text, heading_offset=heading_offset,
|
||||
link_rewrite=make_link_rewrite(site))
|
||||
html = html.replace("<table>", '<div class="table-wrap"><table>')
|
||||
html = html.replace("</table>", "</table></div>")
|
||||
return Markup(html)
|
||||
|
||||
|
||||
def sections_map(text):
|
||||
return dict(md.split_sections(text, level=2))
|
||||
|
||||
|
||||
def render_sections(text, site, titles, *, level=2):
|
||||
"""Render named level-2 sections only, each under its own heading."""
|
||||
found = sections_map(text) if level == 2 else {}
|
||||
out = []
|
||||
for title in titles:
|
||||
body = found.get(title)
|
||||
if body is None:
|
||||
continue
|
||||
out.append(md.render(f"## {title}\n\n{body}", link_rewrite=make_link_rewrite(site)))
|
||||
html = "\n".join(out)
|
||||
html = html.replace("<table>", '<div class="table-wrap"><table>')
|
||||
html = html.replace("</table>", "</table></div>")
|
||||
return Markup(html)
|
||||
|
||||
|
||||
def _record_links(recs):
|
||||
"""The records as a link list, one name per line."""
|
||||
return Markup('<ul class="linklist">' + "".join(
|
||||
f'<li><a href="{esc(common.trail_path(r))}">{common.name(r)}</a></li>' for r in recs) + "</ul>")
|
||||
|
||||
|
||||
def _group_by(records, keyfn):
|
||||
groups = collections.defaultdict(list)
|
||||
for r in records:
|
||||
groups[keyfn(r)].append(r)
|
||||
for recs in groups.values():
|
||||
recs.sort(key=lambda r: r["name"].lower())
|
||||
return groups
|
||||
|
||||
|
||||
def sources_page(records, site, repo_root):
|
||||
"""(title, description, body) for /sources/."""
|
||||
by_licence = _group_by(records, lambda r: r.get("source", {}).get("licence", "") or "unknown")
|
||||
by_source = _group_by(records, lambda r: r.get("source", {}).get("line_source", "") or "none (no line included)")
|
||||
by_status = _group_by(records, lambda r: r.get("source", {}).get("status", "") or "none")
|
||||
|
||||
def measured(recs):
|
||||
return sum(1 for r in recs if r.get("verification", {}).get("verified"))
|
||||
|
||||
n_measured = measured(records)
|
||||
status_cells = (f'<div><dt>Line measured</dt><dd>{n_measured}<small>Records whose line was '
|
||||
f'downloaded and measured (verification), whatever its source</small></dd></div>')
|
||||
for key in ("verified", "osm-only", "found", "none"):
|
||||
recs = by_status.get(key, [])
|
||||
k = measured(recs)
|
||||
of_these = (f"; {k} of these measured" if k and k < len(recs) else
|
||||
"; all measured" if k and k == len(recs) and key != "verified" else "")
|
||||
status_cells += (f'<div><dt>Source status: {esc(words.label(words.SOURCE_STATUS, key))}</dt>'
|
||||
f'<dd>{len(recs)}<small>{esc(words.meaning(words.SOURCE_STATUS, key))}{esc(of_these)}</small></dd></div>')
|
||||
other = [k for k in by_status if k not in ("verified", "osm-only", "found", "none")]
|
||||
|
||||
def group_rows(groups, label_of):
|
||||
rows = ""
|
||||
for key in sorted(groups, key=lambda k: (-len(groups[k]), str(k).lower())):
|
||||
recs = groups[key]
|
||||
lines = sum(1 for r in recs if common.has_line(r))
|
||||
rows += (f'<tr><td>{label_of(key)}</td><td class="num">{len(recs)}</td>'
|
||||
f'<td class="num">{lines}</td><td>{_record_links(recs)}</td></tr>')
|
||||
return rows
|
||||
|
||||
def lic_label(k):
|
||||
return Markup(f'{esc(words.label(words.LICENCES, k))} <code class="raw">{esc(k)}</code>')
|
||||
|
||||
head = ('<thead><tr><th scope="col">{0}</th><th scope="col">Records</th>'
|
||||
'<th scope="col">With a line</th><th scope="col">Trails and routes</th></tr></thead>')
|
||||
computed = f"""<div class="container section">
|
||||
<div class="section-head"><h2 id="sources-at-a-glance">At a glance</h2>
|
||||
<p>Counted from the {len(records)} records. Each trail page names its own source, licence and credit.
|
||||
The source status says where a line was looked for; whether it was measured is counted separately.</p></div>
|
||||
<dl class="tally">{status_cells}</dl>
|
||||
{f'<p class="note">Other source status values: {esc(", ".join(map(str, other)))}.</p>' if other else ""}
|
||||
<div class="doc-block"><h3>By licence</h3><div class="table-wrap"><table>
|
||||
{head.format("Licence")}
|
||||
<tbody>{group_rows(by_licence, lic_label)}</tbody></table></div></div>
|
||||
<div class="doc-block"><h3>By line source</h3><div class="table-wrap"><table>
|
||||
{head.format("Line source")}
|
||||
<tbody>{group_rows(by_source, esc)}</tbody></table></div></div>
|
||||
</div>"""
|
||||
doc_html = render_doc(read_doc(repo_root, "SOURCES.md"), site, drop_h1=True)
|
||||
body = (f'<div class="page-head"><div class="container"><header class="titleblock">'
|
||||
f'<div class="titleblock__text"><p class="kicker">Provenance</p><h1>Sources</h1>'
|
||||
f'<p class="page-head__lede">Where the lines come from, and the terms each source states.</p>'
|
||||
f'</div></header></div></div>{computed}'
|
||||
f'<div class="container section"><div class="prose doc">{doc_html}</div></div>')
|
||||
return "Sources", "Where each trail line comes from: licences, line sources and source terms.", Markup(body)
|
||||
|
||||
|
||||
def logos_page(records, site, repo_root):
|
||||
"""(title, description, body) for /logos/."""
|
||||
notice_html = link_requests(render_sections(read_doc(repo_root, "NOTICE.md"), site,
|
||||
["Logos and marks", "Removal"]), site)
|
||||
with_logo = [r for r in sorted(records, key=lambda r: r["name"].lower())
|
||||
if "shield" in r["derived"]["files"]]
|
||||
cards = ""
|
||||
for r in with_logo:
|
||||
sh = r.get("shield", {})
|
||||
src = sh.get("logo_source", "")
|
||||
if src.startswith(("http://", "https://")):
|
||||
src_html = Markup(f'<a href="{esc(src)}">{esc(src)}</a>')
|
||||
elif src:
|
||||
src_html = esc(src)
|
||||
else:
|
||||
src_html = Markup("Not recorded")
|
||||
cards += f"""<li class="logo-card">
|
||||
{common.plate(r, size="lg", link=True, alt="")}
|
||||
<div><h3><a href="{esc(common.trail_path(r))}">{common.name(r)}</a></h3>
|
||||
<dl class="facts"><div><dt>Holder</dt><dd>{esc(sh.get("logo_owner", "") or "Not recorded")}</dd></div>
|
||||
<div><dt>Taken from</dt><dd>{src_html}</dd></div></dl></div>
|
||||
</li>"""
|
||||
counts = collections.Counter(r.get("shield", {}).get("status", "") for r in records)
|
||||
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
|
||||
<div class="titleblock__text"><p class="kicker">Marks</p><h1>Logos</h1>
|
||||
<p class="page-head__lede">Logos are shown only to identify each trail. They belong to their holders.</p>
|
||||
</div></header></div></div>
|
||||
<div class="container section"><div class="prose doc">{notice_html}</div></div>
|
||||
<div class="container section"><div class="section-head"><h2>Every logo in the dataset</h2>
|
||||
<p>{len(with_logo)} records include a logo file.</p></div>
|
||||
<ul class="logo-grid">{cards}</ul>
|
||||
<p class="note">No logo file is included for the other records: {counts["no-logo-exists"]} are recorded as
|
||||
having no logo (<code class="raw">no-logo-exists</code>) and {counts["logo-not-found"]} as
|
||||
logo not found (<code class="raw">logo-not-found</code>).</p></div>"""
|
||||
return "Logos", "Trail logos, their holders, and how a holder can ask for removal.", Markup(body)
|
||||
|
||||
|
||||
def about_page(records, site, repo_root):
|
||||
"""(title, description, body) for /about/."""
|
||||
readme = read_doc(repo_root, "README.md")
|
||||
main = link_requests(render_sections(readme, site,
|
||||
["What this is, and what it is not", "Inclusion rule",
|
||||
"How to use it", "Report an error", "Licences", "Sources"]), site)
|
||||
contrib = render_doc(read_doc(repo_root, "CONTRIBUTING.md"), site, heading_offset=1)
|
||||
extra = ""
|
||||
if site.issues_url:
|
||||
extra = f'<p><a href="{esc(site.issues_url)}">Open an issue</a> to report an error.</p>'
|
||||
if site.repo_url:
|
||||
extra += f'<p>Source repository: <a href="{esc(site.repo_url)}">{esc(site.repo_url)}</a>.</p>'
|
||||
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
|
||||
<div class="titleblock__text"><p class="kicker">The project</p><h1>About {esc(site.name)}</h1>
|
||||
<p class="page-head__lede">{esc(site.tagline)}.</p></div></header></div></div>
|
||||
<div class="container section"><div class="prose doc">{main}{extra}{contrib}</div></div>"""
|
||||
return "About", f"What {site.name} is and is not, the inclusion rule, licences and how to contribute.", Markup(body)
|
||||
|
||||
|
||||
def _size(out_dir, relpath):
|
||||
path = os.path.join(out_dir, *relpath.split("/"))
|
||||
return words.fmt_bytes(os.path.getsize(path)) if os.path.isfile(path) else "—"
|
||||
|
||||
|
||||
# The bulk files on /data/: (name, what it holds, offered as a download).
|
||||
# trails.json and overview.geojson are what the pages fetch; a browser shows them.
|
||||
BULK_FILES = (
|
||||
("trails.csv", "One row per trail: id, name, country, regions, length, kind, line policy and status.", True),
|
||||
("trails.json", "Every record in full, as JSON, with the derived fields the site builds.", False),
|
||||
("index.geojson", "Every included line, simplified to about 100 m, with id and name.", True),
|
||||
("overview.geojson", "Every included line simplified to about 750 m for the overview map, "
|
||||
"with id, name, kind, country and length.", False),
|
||||
("all-gpx.zip", "Every GPX file (main lines and alternates, simplified to 5 m), as <id>/<file>, "
|
||||
"with each trail's release.txt, trails.csv, SOURCES.md and a README.", True),
|
||||
("all-geojson.zip", "Every full-resolution GeoJSON main line and alternates file, as <id>/<file>, "
|
||||
"with each trail's release.txt, trails.csv, SOURCES.md and a README.", True),
|
||||
)
|
||||
|
||||
|
||||
def _licence_text_url(licence, repo_root):
|
||||
"""Where to read a licence: the copy under /licences/, else the licence's own page, else /sources/."""
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
if os.path.isfile(os.path.join(base, "LICENSES", f"{licence}.txt")):
|
||||
return f"/licences/{licence}.txt"
|
||||
return words.LICENCE_URLS.get(licence, "/sources/")
|
||||
|
||||
|
||||
def line_licence_rows(records, repo_root):
|
||||
"""(what, terms, text URL) for each licence the included lines carry, from the records."""
|
||||
by_licence = _group_by([r for r in records if common.has_line(r)],
|
||||
lambda r: r.get("source", {}).get("licence", "") or "unknown")
|
||||
rows = []
|
||||
for lic in sorted(by_licence, key=lambda k: (-len(by_licence[k]), k.lower())):
|
||||
recs = by_licence[lic]
|
||||
label = words.label(words.LICENCES, lic)
|
||||
n = len(recs)
|
||||
what = f"Lines licensed {esc(label)}: {n} record{'s' if n != 1 else ''}"
|
||||
if n <= 3:
|
||||
links = ", ".join(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>' for r in recs)
|
||||
what += f" ({links})"
|
||||
what = Markup(what)
|
||||
terms = Markup(f'{esc(label)} <code class="raw">{esc(lic)}</code>; credit as named in each record and its release.txt')
|
||||
rows.append((what, terms, _licence_text_url(lic, repo_root)))
|
||||
return rows
|
||||
|
||||
|
||||
def data_page(records, site, repo_root, out_dir):
|
||||
"""(title, description, body) for /data/."""
|
||||
rows = ""
|
||||
for name, what, download in BULK_FILES:
|
||||
dl = f' download="{esc(name)}"' if download else ""
|
||||
rows += (f'<tr><td><a href="/data/{esc(name)}"{dl}>/data/{esc(name)}</a></td>'
|
||||
f'<td>{esc(what)}</td><td class="num">{esc(_size(out_dir, "data/" + name))}</td></tr>')
|
||||
per_trail = [
|
||||
("<id>.geojson", "The main line at full resolution, as published in the dataset."),
|
||||
("<id>.gpx", "The main line simplified to 5 m, for GPS devices. No elevation."),
|
||||
("<id>-alternates.geojson / .gpx", "Alternate and connector lines, where the source serves them separately."),
|
||||
("<id>-<source>.geojson", "One source's own extract, where a line combines sources."),
|
||||
("map.json", "The line simplified to 30 m for the trail page map (GeoJSON)."),
|
||||
("trail.toml", "The record itself: source, licence, verification, logo and route details."),
|
||||
("release.txt", "The source, licence and date the line files came from, where a line is included."),
|
||||
("shield.svg / shield.png", "The trail logo, where one is included. Not licensed; see Logos."),
|
||||
("shield-thumb.png", "A copy of a PNG logo no larger than 256 px, for the lists."),
|
||||
]
|
||||
prow = "".join(f'<tr><td><code>{esc(n)}</code></td><td>{esc(w)}</td></tr>' for n, w in per_trail)
|
||||
lic_rows = [
|
||||
("Records, documents and compiled index", "CC0-1.0 (public domain)", '/licences/LICENSE'),
|
||||
("Tools in tools/", "MIT", '/licences/MIT.txt'),
|
||||
("Each trail line", "Keeps its source's terms, stated in its record; see Sources", '/sources/'),
|
||||
("Lines from OpenStreetMap", "ODbL-1.0; credit © OpenStreetMap contributors", '/licences/ODbL-1.0.txt'),
|
||||
*line_licence_rows(records, repo_root),
|
||||
("Trail logos", "Not licensed; belong to their holders, shown only to identify each trail", '/logos/'),
|
||||
]
|
||||
lrow = "".join(f'<tr><td>{esc(a)}</td><td>{esc(b)}</td><td><a href="{esc(c)}">{esc(c)}</a></td></tr>'
|
||||
for a, b, c in lic_rows)
|
||||
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
|
||||
<div class="titleblock__text"><p class="kicker">Downloads</p><h1>Data</h1>
|
||||
<p class="page-head__lede">Bulk files, the stable per-trail URLs, and the licences.</p></div></header></div></div>
|
||||
<div class="container section">
|
||||
<div class="section-head"><h2>Bulk downloads</h2><p>{len(records)} records. Sizes are this build's.</p></div>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">File</th><th scope="col">What it holds</th><th scope="col">Size</th></tr></thead>
|
||||
<tbody>{rows}</tbody></table></div>
|
||||
<p class="prose">Each line in the archives keeps its source’s terms and needs its source’s
|
||||
credit, as given in the trail’s release.txt; trails.csv gives each record’s licence too.</p>
|
||||
<div class="doc-block"><h2>Per-trail files</h2>
|
||||
<p class="prose">Every record has a stable directory. Replace <code><id></code> with a record id
|
||||
(for example <code>long-trail</code>): <code>/trails/<id>/<id>.geojson</code>,
|
||||
<code>/trails/<id>/<id>.gpx</code>, <code>/trails/<id>/<id>-alternates.geojson</code> (and <code>.gpx</code>),
|
||||
<code>/trails/<id>/map.json</code>, <code>/trails/<id>/trail.toml</code> and
|
||||
<code>/trails/<id>/release.txt</code>. The trail page is <code>/trails/<id>/</code>.
|
||||
Line files exist only where the record includes a line; the record says why when it does not.</p>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">File under /trails/<id>/</th><th scope="col">What it holds</th></tr></thead>
|
||||
<tbody>{prow}</tbody></table></div></div>
|
||||
<div class="doc-block"><h2>Licences</h2>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">What</th><th scope="col">Terms</th><th scope="col">Text</th></tr></thead>
|
||||
<tbody>{lrow}</tbody></table></div>
|
||||
<p class="prose">Licence texts: <a href="/licences/LICENSE">CC0-1.0 (LICENSE)</a>,
|
||||
<a href="/licences/CC0-1.0.txt">CC0-1.0.txt</a>, <a href="/licences/MIT.txt">MIT.txt</a>,
|
||||
<a href="/licences/CC-BY-4.0.txt">CC-BY-4.0.txt</a>, <a href="/licences/ODbL-1.0.txt">ODbL-1.0.txt</a>.</p></div>
|
||||
<div class="doc-block"><h2>Reference</h2><ul class="linklist doc-links">
|
||||
<li><a href="/data/schema/">Record schema</a><small>Every field of trail.toml</small></li>
|
||||
<li><a href="/data/changelog/">Changelog</a><small>What changed, release by release</small></li>
|
||||
<li><a href="/sources/">Sources</a><small>Each source, its terms and the trails that use it</small></li>
|
||||
</ul></div>
|
||||
</div>"""
|
||||
return "Data", "Bulk downloads, stable per-trail file URLs, the record schema and licences.", Markup(body)
|
||||
|
||||
|
||||
def schema_page(site, repo_root):
|
||||
doc_html = render_doc(read_doc(repo_root, "docs/schema.md"), site, drop_h1=True)
|
||||
body = f"""<div class="page-head"><div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/data/">Data</a></li>
|
||||
<li aria-current="page">Record schema</li></ol></nav>
|
||||
<header class="titleblock"><div class="titleblock__text"><p class="kicker">Reference</p>
|
||||
<h1>Record schema</h1></div></header></div></div>
|
||||
<div class="container section"><div class="prose doc">{doc_html}</div></div>"""
|
||||
return "Record schema", "Every field of a trail record (trail.toml) and what it means.", Markup(body)
|
||||
|
||||
|
||||
def changelog_page(site, repo_root):
|
||||
doc_html = render_doc(read_doc(repo_root, "CHANGELOG.md"), site, drop_h1=True)
|
||||
body = f"""<div class="page-head"><div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/data/">Data</a></li>
|
||||
<li aria-current="page">Changelog</li></ol></nav>
|
||||
<header class="titleblock"><div class="titleblock__text"><p class="kicker">Reference</p>
|
||||
<h1>Changelog</h1></div></header></div></div>
|
||||
<div class="container section"><div class="prose doc">{doc_html}</div></div>"""
|
||||
return "Changelog", "What changed in the dataset, release by release.", Markup(body)
|
||||
|
||||
|
||||
def copy_licences(out_dir, repo_root):
|
||||
"""Copy LICENSE and LICENSES/*.txt to /licences/. Returns file names copied."""
|
||||
import shutil
|
||||
dest = os.path.join(out_dir, "licences")
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
copied = []
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
lic = os.path.join(base, "LICENSE")
|
||||
if os.path.isfile(lic):
|
||||
shutil.copyfile(lic, os.path.join(dest, "LICENSE"))
|
||||
copied.append("LICENSE")
|
||||
break
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
d = os.path.join(base, "LICENSES")
|
||||
if os.path.isdir(d):
|
||||
for name in sorted(os.listdir(d)):
|
||||
if name.endswith(".txt"):
|
||||
shutil.copyfile(os.path.join(d, name), os.path.join(dest, name))
|
||||
copied.append(name)
|
||||
break
|
||||
return copied
|
||||
@@ -0,0 +1,307 @@
|
||||
"""Line geometry helpers: reading GeoJSON, length, bbox, simplification, GPX.
|
||||
|
||||
Python 3 standard library only. A "part" is a list of coordinates, each
|
||||
[lon, lat] or [lon, lat, ele]; a line is a list of parts.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
from xml.sax.saxutils import escape, quoteattr
|
||||
|
||||
EARTH_R = 6371008.8 # metres
|
||||
LICENCE_URLS = {
|
||||
"us-gov-public-domain": "https://www.usa.gov/government-works",
|
||||
"CC-BY-4.0": "https://creativecommons.org/licenses/by/4.0/",
|
||||
"CC-BY": "https://creativecommons.org/licenses/by/4.0/",
|
||||
"ODbL-1.0": "https://opendatacommons.org/licenses/odbl/1-0/",
|
||||
}
|
||||
|
||||
|
||||
def read_parts(path):
|
||||
"""Read a GeoJSON file; return its LineString and MultiLineString parts."""
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return parts_from_geojson(data)
|
||||
|
||||
|
||||
def parts_from_geojson(data):
|
||||
if data.get("type") == "FeatureCollection":
|
||||
geoms = [(f.get("geometry") or {}) for f in data.get("features", [])]
|
||||
elif data.get("type") == "Feature":
|
||||
geoms = [data.get("geometry") or {}]
|
||||
else:
|
||||
geoms = [data]
|
||||
parts = []
|
||||
for geom in geoms:
|
||||
gtype = geom.get("type")
|
||||
if gtype == "LineString":
|
||||
parts.append(geom["coordinates"])
|
||||
elif gtype == "MultiLineString":
|
||||
parts.extend(geom["coordinates"])
|
||||
return [p for p in parts if len(p) >= 2]
|
||||
|
||||
|
||||
def point_count(parts):
|
||||
return sum(len(p) for p in parts)
|
||||
|
||||
|
||||
def length_km(parts):
|
||||
"""Geodesic (haversine) length of all parts, in kilometres."""
|
||||
total = 0.0
|
||||
for coords in parts:
|
||||
lon1, lat1 = math.radians(coords[0][0]), math.radians(coords[0][1])
|
||||
for c in coords[1:]:
|
||||
lon2, lat2 = math.radians(c[0]), math.radians(c[1])
|
||||
a = (math.sin((lat2 - lat1) / 2) ** 2
|
||||
+ math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2)
|
||||
total += 2 * EARTH_R * math.asin(min(1.0, math.sqrt(a)))
|
||||
lon1, lat1 = lon2, lat2
|
||||
return total / 1000.0
|
||||
|
||||
|
||||
def bbox(parts):
|
||||
"""[min lon, min lat, max lon, max lat], or None when there are no points."""
|
||||
xs = [c[0] for p in parts for c in p]
|
||||
ys = [c[1] for p in parts for c in p]
|
||||
if not xs:
|
||||
return None
|
||||
return [min(xs), min(ys), max(xs), max(ys)]
|
||||
|
||||
|
||||
def merge_bbox(boxes):
|
||||
boxes = [b for b in boxes if b]
|
||||
if not boxes:
|
||||
return None
|
||||
return [min(b[0] for b in boxes), min(b[1] for b in boxes),
|
||||
max(b[2] for b in boxes), max(b[3] for b in boxes)]
|
||||
|
||||
|
||||
def _gap_m(a, b):
|
||||
"""Approximate distance in metres between two [lon, lat] points."""
|
||||
dx = (a[0] - b[0]) * math.cos(math.radians((a[1] + b[1]) / 2))
|
||||
return math.hypot(dx, a[1] - b[1]) * math.pi / 180.0 * EARTH_R
|
||||
|
||||
|
||||
def join_parts(parts, gap_m=100.0):
|
||||
"""Chain parts whose end points lie within gap_m of each other.
|
||||
|
||||
Greedy: each chain grows at its tail, then at its head, taking the nearest
|
||||
unused part end each time (a part is reversed when its far end is the
|
||||
near one). Parts that touch nothing stay as they are.
|
||||
|
||||
Ends are bucketed in a metre-scaled grid: longitude is multiplied by the
|
||||
cosine of the highest latitude in the data and both axes use metres, so a
|
||||
grid step is never longer than gap_m on the ground. A fixed step in
|
||||
degrees would miss joins at high latitude, where gap_m spans more than one
|
||||
cell of longitude; here the neighbour scan of plus or minus one cell is
|
||||
correct at any latitude.
|
||||
"""
|
||||
if not parts:
|
||||
return []
|
||||
cell = max(gap_m, 1.0)
|
||||
k = math.pi / 180.0 * EARTH_R
|
||||
max_lat = max(abs(c[1]) for p in parts for c in (p[0], p[-1]))
|
||||
scale = max(math.cos(math.radians(max_lat)), 1e-9) * k
|
||||
|
||||
def cell_of(c):
|
||||
return (math.floor(c[0] * scale / cell), math.floor(c[1] * k / cell))
|
||||
|
||||
grid = {}
|
||||
for i, p in enumerate(parts):
|
||||
for end in (0, 1):
|
||||
c = p[0] if end == 0 else p[-1]
|
||||
grid.setdefault(cell_of(c), []).append((i, end))
|
||||
used = [False] * len(parts)
|
||||
|
||||
def nearest(point):
|
||||
gx, gy = cell_of(point)
|
||||
best = None
|
||||
for x in (gx - 1, gx, gx + 1):
|
||||
for y in (gy - 1, gy, gy + 1):
|
||||
for i, end in grid.get((x, y), ()):
|
||||
if used[i]:
|
||||
continue
|
||||
c = parts[i][0] if end == 0 else parts[i][-1]
|
||||
d = _gap_m(point, c)
|
||||
if d <= gap_m and (best is None or d < best[0]):
|
||||
best = (d, i, end)
|
||||
return best
|
||||
|
||||
out = []
|
||||
for i0, first in enumerate(parts):
|
||||
if used[i0]:
|
||||
continue
|
||||
used[i0] = True
|
||||
chain = list(first)
|
||||
while True: # grow the tail
|
||||
hit = nearest(chain[-1])
|
||||
if hit is None:
|
||||
break
|
||||
_, i, end = hit
|
||||
used[i] = True
|
||||
chain.extend(parts[i] if end == 0 else parts[i][::-1])
|
||||
while True: # grow the head
|
||||
hit = nearest(chain[0])
|
||||
if hit is None:
|
||||
break
|
||||
_, i, end = hit
|
||||
used[i] = True
|
||||
chain[:0] = parts[i][::-1] if end == 0 else parts[i]
|
||||
out.append(chain)
|
||||
return out
|
||||
|
||||
|
||||
def simplify_part(coords, tol_m):
|
||||
"""Douglas-Peucker with an explicit stack; tol_m is in metres.
|
||||
|
||||
Distances are measured on a local equirectangular plane for the segment
|
||||
being tested, scaled by the mean cosine at its two ends. A single scale for
|
||||
a whole part would understate distances when the part runs hundreds of
|
||||
kilometres north to south; taking the cosine per segment bounds the
|
||||
residual error by the change in cosine across that segment.
|
||||
|
||||
When a segment spans enough latitude that its two ends differ in cosine by
|
||||
more than 1%, distances are instead measured in a tangent plane centred on
|
||||
each candidate point (east = (lon - lon_point) * cos(point latitude)).
|
||||
That is the exact local metric, so even a very long north-south segment
|
||||
cannot drop a point whose true distance exceeds the tolerance. Short
|
||||
segments, where the two methods agree to within 1%, use the cheaper shared
|
||||
scale; 1% of the tolerance is a few centimetres at the 5 m GPX tolerance.
|
||||
|
||||
The end points are always kept; only interior points are dropped, and the
|
||||
kept points are the originals. The algorithm is iterative, and the plane
|
||||
origin is folded into precomputed arrays so the inner loop stays cheap
|
||||
enough for parts with hundreds of thousands of points.
|
||||
"""
|
||||
n = len(coords)
|
||||
if n < 3:
|
||||
return list(coords)
|
||||
k = math.pi / 180.0 * EARTH_R
|
||||
lons = [c[0] for c in coords]
|
||||
lats = [c[1] for c in coords]
|
||||
# Metres per degree of longitude (ck) and metres north (ys), per point.
|
||||
ck = [math.cos(math.radians(lat)) * k for lat in lats]
|
||||
ys = [lat * k for lat in lats]
|
||||
tol2 = tol_m * tol_m
|
||||
keep = bytearray(n)
|
||||
keep[0] = keep[n - 1] = 1
|
||||
stack = [(0, n - 1)]
|
||||
while stack:
|
||||
a, b = stack.pop()
|
||||
if b - a < 2:
|
||||
continue
|
||||
la, lb = lons[a], lons[b]
|
||||
dlon = lb - la
|
||||
ya, yb = ys[a], ys[b]
|
||||
dy = yb - ya
|
||||
ca, cb = ck[a], ck[b]
|
||||
# Relative change in cosine across the segment. Below 1% one scale for
|
||||
# the whole segment is as accurate as the tolerance needs (a point
|
||||
# within tol_m of the segment is within a few metres of its latitude,
|
||||
# so the scale error at that point is no larger than this).
|
||||
shared = abs(ca - cb) <= 0.01 * (ca if ca > cb else cb)
|
||||
cm = 0.5 * (ca + cb) if shared else 0.0
|
||||
best, idx = -1.0, -1
|
||||
for i in range(a + 1, b):
|
||||
ci = cm if shared else ck[i]
|
||||
ax = (la - lons[i]) * ci # a, relative to the plane origin
|
||||
ay = ya - ys[i]
|
||||
dx = dlon * ci
|
||||
len2 = dx * dx + dy * dy
|
||||
if len2 == 0.0:
|
||||
d2 = ax * ax + ay * ay
|
||||
else:
|
||||
u = -(ax * dx + ay * dy) / len2
|
||||
if u <= 0.0:
|
||||
d2 = ax * ax + ay * ay
|
||||
elif u >= 1.0:
|
||||
ex, ey = ax + dx, ay + dy
|
||||
d2 = ex * ex + ey * ey
|
||||
else:
|
||||
cross = ax * dy - ay * dx
|
||||
d2 = cross * cross / len2
|
||||
if d2 > best:
|
||||
best, idx = d2, i
|
||||
if best > tol2:
|
||||
keep[idx] = 1
|
||||
stack.append((a, idx))
|
||||
stack.append((idx, b))
|
||||
return [c for c, k_ in zip(coords, keep) if k_]
|
||||
|
||||
|
||||
def simplify(parts, tol_m):
|
||||
return [simplify_part(p, tol_m) for p in parts]
|
||||
|
||||
|
||||
def round_coords(parts, decimals):
|
||||
"""Round lon and lat (elevation is kept); drop repeated neighbours.
|
||||
|
||||
A part that rounds down to fewer than two distinct points is dropped
|
||||
entirely: a zero-length part is not useful on a map or in a GPX track
|
||||
segment, and keeping two copies of one coordinate would produce one.
|
||||
"""
|
||||
out = []
|
||||
for coords in parts:
|
||||
new = []
|
||||
last = None
|
||||
for c in coords:
|
||||
r = [round(c[0], decimals), round(c[1], decimals)] + list(c[2:])
|
||||
key = (r[0], r[1])
|
||||
if key != last:
|
||||
new.append(r)
|
||||
last = key
|
||||
if len(new) >= 2:
|
||||
out.append(new)
|
||||
return out
|
||||
|
||||
|
||||
def has_elevation(parts):
|
||||
return any(len(c) > 2 for p in parts for c in p)
|
||||
|
||||
|
||||
def _num(v):
|
||||
"""Plain decimal text (no exponent, as GPX requires) for a number."""
|
||||
text = f"{float(v):.8f}".rstrip("0").rstrip(".")
|
||||
return "0" if text in ("", "-0") else text
|
||||
|
||||
|
||||
def gpx_text(parts, name, url="", attribution="", licence="", licence_text="",
|
||||
creator="long-trails dataset"):
|
||||
"""GPX 1.1 with one <trk> and one <trkseg> per part."""
|
||||
desc = []
|
||||
if attribution:
|
||||
desc.append(f"Attribution: {attribution}")
|
||||
if licence_text:
|
||||
desc.append(f"Licence: {licence_text}")
|
||||
elif licence:
|
||||
desc.append(f"Licence: {licence}")
|
||||
out = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
f'<gpx version="1.1" creator={quoteattr(creator)} '
|
||||
'xmlns="http://www.topografix.com/GPX/1/1">',
|
||||
"<metadata>",
|
||||
f"<name>{escape(name)}</name>",
|
||||
]
|
||||
if desc:
|
||||
out.append(f"<desc>{escape(' '.join(desc))}</desc>")
|
||||
if attribution:
|
||||
out.append(f"<copyright author={quoteattr(attribution)}>")
|
||||
if licence in LICENCE_URLS:
|
||||
out.append(f"<license>{escape(LICENCE_URLS[licence])}</license>")
|
||||
out.append("</copyright>")
|
||||
if url:
|
||||
out.append(f"<link href={quoteattr(url)}/>")
|
||||
out.append("</metadata>")
|
||||
out.append("<trk>")
|
||||
out.append(f"<name>{escape(name)}</name>")
|
||||
for coords in parts:
|
||||
out.append("<trkseg>")
|
||||
for c in coords:
|
||||
head = f'<trkpt lat="{_num(c[1])}" lon="{_num(c[0])}"'
|
||||
if len(c) > 2:
|
||||
out.append(f"{head}><ele>{_num(c[2])}</ele></trkpt>")
|
||||
else:
|
||||
out.append(f"{head}/>")
|
||||
out.append("</trkseg>")
|
||||
out.append("</trk>")
|
||||
out.append("</gpx>")
|
||||
return "\n".join(out) + "\n"
|
||||
@@ -0,0 +1,370 @@
|
||||
"""The home page: what the site is, the overview map, and the trail finder with every record.
|
||||
|
||||
The list of records (results(), entry()) is shared with the region pages and
|
||||
the routes page, so every list of records on the site looks and reads the same.
|
||||
"""
|
||||
import collections
|
||||
import math
|
||||
import re
|
||||
|
||||
from . import common, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
# Length range choices (km) for the filters. length_steps() adds a top step
|
||||
# above the longest record, so a chosen upper bound can always reach every record.
|
||||
LENGTH_STEPS = (60, 80, 100, 150, 200, 300, 500, 1000, 2000, 4000, 8000)
|
||||
|
||||
|
||||
def length_steps(records):
|
||||
"""LENGTH_STEPS plus a round step at or above the longest record, when that is longer."""
|
||||
longest = max((r["length_km"] for r in records), default=0)
|
||||
steps = list(LENGTH_STEPS)
|
||||
if longest > steps[-1]:
|
||||
magnitude = 10 ** int(math.floor(math.log10(longest)))
|
||||
steps.append(int(math.ceil(longest / magnitude) * magnitude))
|
||||
return steps
|
||||
|
||||
|
||||
def counts(records):
|
||||
"""Counts for the filters. A record counts under each country it touches (its own
|
||||
country and its regions' countries) and under each of its regions, as on /regions/;
|
||||
a Canada-wide record counts under "region:CA-*", not under each province."""
|
||||
c = collections.Counter()
|
||||
for r in records:
|
||||
c["total"] += 1
|
||||
c[common.kind(r)] += 1
|
||||
c["line" if common.has_line(r) else "record_only"] += 1
|
||||
if common.is_route(r):
|
||||
c["route_line" if common.has_line(r) else "route_record_only"] += 1
|
||||
c["policy:" + common.policy(r)] += 1
|
||||
c["tier:" + r.get("tier", "")] += 1
|
||||
for country in common.countries(r):
|
||||
c["country:" + country] += 1
|
||||
for key in set(words.region_key(code, r["country"]) for code in r.get("regions", [])):
|
||||
c["region:" + key] += 1
|
||||
return c
|
||||
|
||||
|
||||
def overview_bbox(records):
|
||||
"""data-bbox attribute: the extent of every line, so the map opens on it before the data loads."""
|
||||
boxes = [r["derived"]["bbox"] for r in records if r["derived"].get("bbox")]
|
||||
if not boxes:
|
||||
return ""
|
||||
box = [min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)]
|
||||
return f' data-bbox="{",".join(f"{v:.4f}" for v in box)}"'
|
||||
|
||||
|
||||
def sort_name(rec):
|
||||
return re.sub(r"^The ", "", rec["name"]).lower()
|
||||
|
||||
|
||||
def entry(rec, *, level=3, extra=""):
|
||||
"""One record in a list. Its data-* attributes drive the filters in app.js.
|
||||
|
||||
level: the heading level of the record's name. extra: HTML placed last in the row.
|
||||
"""
|
||||
route = common.is_route(rec)
|
||||
if route:
|
||||
r = rec["route"]
|
||||
desc = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "")
|
||||
elif rec.get("tier") == "national" and common.designated_year(rec):
|
||||
desc = "Designated " + common.designated_year(rec)
|
||||
else:
|
||||
desc = rec.get("designation", "")
|
||||
where = Markup(f'{common.regions_html(rec, linked=True)} <span aria-hidden="true">·</span> '
|
||||
f'{esc(words.COUNTRIES.get(rec["country"], rec["country"]))}')
|
||||
policy = common.policy_chip(common.policy(rec)) if route else ""
|
||||
partial = common.line_differs(rec)
|
||||
if common.has_line(rec):
|
||||
partial_note = (f'<p class="entry__partial">{esc(common.partial_short_text(rec))}</p>'
|
||||
if partial else "")
|
||||
line = (f'<span class="line__status">{common.SWATCH_ROUTE if route else common.SWATCH_LINE}Line{policy}</span>'
|
||||
f'{partial_note}'
|
||||
f'<span class="line__detail">GeoJSON, GPX</span>'
|
||||
f'<span class="line__detail">{esc(common.short_source(rec))} · {esc(common.licence_label(rec))}</span>')
|
||||
note = ""
|
||||
else:
|
||||
line = f'<span class="line__status">{common.SWATCH_NONE}Record only{policy}</span>'
|
||||
note = (f'\n <p class="entry__note"><span class="vh">Why there is no line: </span>'
|
||||
f'{esc(common.absent_reason_short(rec))}</p>')
|
||||
regions = " ".join(words.region_key(c, rec["country"]) for c in rec.get("regions", []))
|
||||
search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"]]
|
||||
+ ([rec["route"]["creator"]] if route else [])).lower()
|
||||
abbr_cls = "entry__abbr" if common.shield_url(rec) else "entry__abbr vh"
|
||||
data = (f' data-id="{esc(rec["id"])}" data-country="{esc(rec["country"])}"'
|
||||
f' data-countries="{esc(" ".join(common.countries(rec)))}" data-regions="{esc(regions)}"'
|
||||
f' data-km="{rec["length_km"]}" data-kind="{esc(common.kind(rec))}"'
|
||||
f' data-line="{"yes" if common.has_line(rec) else "no"}"{' data-partial="yes"' if partial else ""}'
|
||||
f' data-tier="{esc(rec.get("tier", ""))}"'
|
||||
f' data-policy="{esc(common.policy(rec))}" data-name="{esc(sort_name(rec))}" data-search="{esc(search)}"')
|
||||
h = f"h{level}"
|
||||
return f"""<li class="entry"{data}>
|
||||
{common.plate(rec)}
|
||||
<div class="entry__body">
|
||||
<p class="entry__kicker">{common.tags(rec, with_policy=False)}</p>
|
||||
<{h} class="entry__name"><a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a> <span class="{abbr_cls}">{esc(rec.get("short_name", ""))}</span></{h}>
|
||||
<p class="entry__desc">{esc(desc)}</p>
|
||||
<p class="entry__where">{where}</p>
|
||||
</div>
|
||||
<dl class="entry__facts">
|
||||
<div class="entry__length"><dt>Length</dt><dd>{words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}<span class="loglen" style="--km: {rec["length_km"]}" aria-hidden="true"></span></dd></div>
|
||||
<div class="entry__line"><dt>Line</dt><dd class="line line--{"yes" if common.has_line(rec) else "no"}">{line}</dd></div>
|
||||
</dl>{note}{extra}
|
||||
</li>"""
|
||||
|
||||
|
||||
def _length_options(steps, selected_any_last):
|
||||
opts = [f'<option value="{km}">{km:,} km · {words.fmt_int(words.km_to_mi(km))} mi</option>'
|
||||
for km in steps]
|
||||
if selected_any_last:
|
||||
return "".join(opts[1:]) + '<option value="" selected>Any</option>'
|
||||
return '<option value="">Any</option>' + "".join(opts[:-1])
|
||||
|
||||
|
||||
def region_options(c):
|
||||
"""The region filter: each state, province and territory a record names, with the
|
||||
count its /regions/ page shows; the Canada-wide records under their own option."""
|
||||
groups = []
|
||||
for country, table in (("US", words.US_STATES), ("CA", words.CA_PROVINCES)):
|
||||
opts = []
|
||||
if country == "CA" and c["region:CA-*"]:
|
||||
key = words.region_key(words.ALL_CANADA, "CA")
|
||||
opts.append(f'<option value="{esc(key)}">{esc(words.region_name(words.ALL_CANADA))} '
|
||||
f'({c["region:" + key]})</option>')
|
||||
for code, name in sorted(table.items(), key=lambda kv: kv[1]):
|
||||
n = c[f"region:{country}-{code}"]
|
||||
if n:
|
||||
opts.append(f'<option value="{country}-{code}">{esc(name)} ({n})</option>')
|
||||
groups.append(f'<optgroup label="{esc(words.COUNTRIES[country])}" data-country="{country}">{"".join(opts)}</optgroup>')
|
||||
return "".join(groups)
|
||||
|
||||
|
||||
def finder_form(c, steps=LENGTH_STEPS):
|
||||
tier_opts = "".join(
|
||||
f'<option value="{t}">{esc(words.label(words.TIERS, t))} ({c["tier:" + t]})</option>'
|
||||
for t in ("national", "regional", "short", "deferred", "candidate") if c["tier:" + t])
|
||||
policy_opts = "".join(
|
||||
f'<option value="{p}">{esc(words.label(words.POLICIES, p))}: {esc(words.meaning(words.POLICIES, p).lower())} ({c["policy:" + p]})</option>'
|
||||
for p in ("open", "sold", "withheld", "unclear") if c["policy:" + p])
|
||||
return f"""<form class="filters" id="finder-form" role="search" aria-label="Find a trail">
|
||||
<div class="filters__search field">
|
||||
<label class="field__label" for="q">Search</label>
|
||||
<input class="input" id="q" name="q" type="search" placeholder="Name, abbreviation or creator" autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="check">
|
||||
<input type="checkbox" name="line">
|
||||
<span class="check__text">Has a downloadable line <span class="check__count">{c["line"]}</span></span>
|
||||
<span class="check__hint">GeoJSON and GPX. The other {c["record_only"]} are records only.</span>
|
||||
</label>
|
||||
</div>
|
||||
<details class="filters__more">
|
||||
<summary>Filters <span class="filters__active"></span></summary>
|
||||
<div class="filters__form">
|
||||
<fieldset class="field">
|
||||
<legend>Country</legend>
|
||||
<div class="seg">
|
||||
<label><input type="radio" name="country" value="all" checked><span>Both ({c["total"]})</span></label>
|
||||
<label><input type="radio" name="country" value="US"><span>United States ({c["country:US"]})</span></label>
|
||||
<label><input type="radio" name="country" value="CA"><span>Canada ({c["country:CA"]})</span></label>
|
||||
</div>
|
||||
<p class="field__hint">A record that crosses the border counts under both.</p>
|
||||
</fieldset>
|
||||
<div class="field">
|
||||
<label class="field__label" for="region">State, province or territory</label>
|
||||
<select class="select" id="region" name="region"><option value="">Any</option>{region_options(c)}</select>
|
||||
</div>
|
||||
<fieldset class="field field--wide">
|
||||
<legend>Length</legend>
|
||||
<div class="range">
|
||||
<label class="vh" for="min">Shortest length</label>
|
||||
<select class="select" id="min" name="min" data-length-options>{_length_options(steps, False)}</select>
|
||||
<span class="range__to" aria-hidden="true">to</span>
|
||||
<label class="vh" for="max">Longest length</label>
|
||||
<select class="select" id="max" name="max" data-length-options>{_length_options(steps, True)}</select>
|
||||
</div>
|
||||
<p class="field__hint" id="len-hint" aria-live="polite">Any length.</p>
|
||||
</fieldset>
|
||||
<fieldset class="field">
|
||||
<legend>Kind</legend>
|
||||
<label class="check">
|
||||
<input type="checkbox" name="designated" checked>
|
||||
<span class="check__text">Designated trails <span class="check__count">{c["designated"]}</span></span>
|
||||
<span class="check__hint">Designated by a land agency or a trail association</span>
|
||||
</label>
|
||||
<label class="check">
|
||||
<input type="checkbox" name="route" checked>
|
||||
<span class="check__text">Person-defined routes <span class="check__count">{c["route"]}</span></span>
|
||||
<span class="check__hint">Worked out and published by a person or a small group</span>
|
||||
</label>
|
||||
<label class="field__label field__label--sub" for="policy">Route line policy</label>
|
||||
<select class="select" id="policy" name="policy"><option value="">Any</option>{policy_opts}</select>
|
||||
</fieldset>
|
||||
<div class="field">
|
||||
<label class="field__label" for="tier">Tier</label>
|
||||
<select class="select" id="tier" name="tier"><option value="">Any</option>{tier_opts}</select>
|
||||
</div>
|
||||
<div class="field field--wide">
|
||||
<button class="button button--quiet" type="reset">Clear search and filters</button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</form>"""
|
||||
|
||||
|
||||
# The length strip's ticks (style.css .loglen): 100, 1,000 and 10,000 km.
|
||||
SCALE_KM = (100, 1000, 10000)
|
||||
|
||||
|
||||
def list_head():
|
||||
"""The column head over a list. The scale ticks follow the reader's unit preference
|
||||
with the same len__km / len__mi pair the lengths use."""
|
||||
ticks = []
|
||||
for i, km in enumerate(SCALE_KM):
|
||||
unit = " km" if i == len(SCALE_KM) - 1 else ""
|
||||
mi_unit = " mi" if i == len(SCALE_KM) - 1 else ""
|
||||
ticks.append(f'<span><span class="len__km">{km:,}{unit}</span>'
|
||||
f'<span class="len__mi">{words.fmt_int(words.km_to_mi(km))}{mi_unit}</span></span>')
|
||||
return f"""<div class="list-head" aria-hidden="true">
|
||||
<span>Trail</span>
|
||||
<span>Length<span class="list-head__scale">{"".join(ticks)}</span></span>
|
||||
<span>Line</span>
|
||||
</div>"""
|
||||
|
||||
|
||||
UNITS_TOGGLE = """<fieldset class="results-units">
|
||||
<legend class="vh">Lengths</legend>
|
||||
<div class="seg seg--small">
|
||||
<label><input type="radio" name="units-list" value="km" checked><span>km</span></label>
|
||||
<label><input type="radio" name="units-list" value="mi"><span>mi</span></label>
|
||||
</div>
|
||||
</fieldset>"""
|
||||
|
||||
SORT_SELECT = """<label class="results-sort">Sort
|
||||
<select class="select" id="sort" name="sort">
|
||||
<option value="name">Name, A to Z</option>
|
||||
<option value="long">Longest first</option>
|
||||
<option value="short">Shortest first</option>
|
||||
</select>
|
||||
</label>"""
|
||||
|
||||
|
||||
def key():
|
||||
return f"""<ul class="key" aria-label="Key to the list">
|
||||
<li>{common.SWATCH_LINE}Line in the dataset</li>
|
||||
<li>{common.SWATCH_NONE}Record only; the note says why</li>
|
||||
<li>Route line policy:
|
||||
{common.policy_chip("open")} {common.policy_chip("sold")} {common.policy_chip("withheld")} {common.policy_chip("unclear")}
|
||||
</li>
|
||||
</ul>"""
|
||||
|
||||
|
||||
def results(recs=None, *, finder=False, groups=None):
|
||||
"""The list of records, as every page shows it: div.results > head, key, list head, ol.entries.
|
||||
|
||||
finder: the home page's list, driven by the finder form (live count, sort, empty state).
|
||||
groups: [(heading, records, extra_fn)] to list the records under level-3 headings
|
||||
(the routes page); extra_fn(rec) gives HTML placed last in each row.
|
||||
"""
|
||||
if groups is None:
|
||||
groups = [(None, recs, None)]
|
||||
total = sum(len(g[1]) for g in groups)
|
||||
noun = "record" if total == 1 else "records"
|
||||
lists = ""
|
||||
for heading, items, extra_fn in groups:
|
||||
level = 4 if heading else 3
|
||||
rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "") for r in items)
|
||||
if heading:
|
||||
lists += f'\n <h3 class="results__group">{heading}</h3>'
|
||||
list_id = ' id="entries"' if finder else ""
|
||||
lists += f'\n <ol class="entries"{list_id}>\n{rows}\n </ol>'
|
||||
if finder:
|
||||
count = (f'<p class="results-count" id="results-count" role="status">'
|
||||
f'<strong>{total}</strong> of {total} {noun}</p>')
|
||||
tools = SORT_SELECT + "\n " + UNITS_TOGGLE
|
||||
empty = """
|
||||
<div class="empty-state" id="empty-state" hidden>
|
||||
<p><strong>No records match these filters.</strong></p>
|
||||
<button class="button button--quiet" type="button" data-reset>Clear search and filters</button>
|
||||
</div>"""
|
||||
else:
|
||||
count = f'<p class="results-count"><strong>{total}</strong> {noun}</p>'
|
||||
tools = UNITS_TOGGLE
|
||||
empty = ""
|
||||
return Markup(f"""<div class="results">
|
||||
<div class="results-head">
|
||||
{count}
|
||||
<div class="results-tools">
|
||||
{tools}
|
||||
</div>
|
||||
</div>
|
||||
{key()}
|
||||
{list_head()}{lists}{empty}
|
||||
</div>""")
|
||||
|
||||
|
||||
def render(records, site):
|
||||
"""The home page body (HTML) for every record."""
|
||||
c = counts(records)
|
||||
recs = sorted(records, key=sort_name)
|
||||
total = c["total"]
|
||||
lede = (f"A record for each of {total} long trails and routes, as a rule 50 miles (80 km) or more: "
|
||||
"what it is, how long it is, who publishes it, and on what terms its line may be passed on. "
|
||||
"Where the terms allow, download the line as GeoJSON or GPX.")
|
||||
return f"""<section class="hero" aria-labelledby="hero-title">
|
||||
<div class="container hero__inner">
|
||||
<p class="kicker">A public dataset · United States and Canada</p>
|
||||
<h1 id="hero-title">{esc(site.tagline)}</h1>
|
||||
<p class="hero__lede">{lede}</p>
|
||||
<p class="hero__caveat">This is a dataset, not a navigation product. Lines vary in quality, some trails are unfinished, and some records have no line at all; each of those says why.</p>
|
||||
<p><a class="button button--primary hero__cta" href="#q">Find a trail</a></p>
|
||||
<div class="hero__counts">
|
||||
<dl class="tally">
|
||||
<div><dt>Records</dt><dd>{total}</dd></div>
|
||||
<div><dt><a href="/?kind=designated">Designated trails</a></dt><dd>{c["designated"]}</dd></div>
|
||||
<div><dt><a href="/?kind=route">Person-defined routes</a></dt><dd>{c["route"]}</dd></div>
|
||||
<div><dt>{common.SWATCH_LINE}<a href="/?line=1">With a line</a></dt><dd>{c["line"]}</dd></div>
|
||||
<div><dt>{common.SWATCH_NONE}Records only</dt><dd>{c["record_only"]}</dd></div>
|
||||
</dl>
|
||||
<div class="ratio" aria-hidden="true"><span class="ratio__line" style="--n: {c["line"]}"></span><span class="ratio__none" style="--n: {c["record_only"]}"></span></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section" aria-labelledby="map-title">
|
||||
<div class="container">
|
||||
<div class="section-head">
|
||||
<h2 id="map-title">Every line in the dataset</h2>
|
||||
<p>{c["line"]} lines, simplified for display. Select a line for its name.</p>
|
||||
</div>
|
||||
<figure class="mapfig" data-map="overview" data-src="/data/overview.geojson"{overview_bbox(records)}>
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
|
||||
<div class="map" role="region" aria-label="Map of every line in the dataset">
|
||||
<div class="map__fallback"></div>
|
||||
<div class="map__canvas"></div>
|
||||
<p class="map__status" role="status">The map needs JavaScript. The list below has every record.</p>
|
||||
</div>
|
||||
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
|
||||
</div>
|
||||
<figcaption class="mapfig__caption">
|
||||
<ul class="legend" aria-label="Legend">
|
||||
<li>{common.SWATCH_LINE}Designated trail</li>
|
||||
<li>{common.SWATCH_ROUTE}Person-defined route</li>
|
||||
</ul>
|
||||
<p>Lines are simplified to about 750 m here; each keeps the credit and licence named on its page. Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section" id="finder" aria-labelledby="finder-title">
|
||||
<div class="container finder__grid">
|
||||
<div class="finder__head section-head">
|
||||
<h2 id="finder-title">Find a trail</h2>
|
||||
<p>Search, then narrow by country, region, length, kind and line</p>
|
||||
</div>
|
||||
{finder_form(c, length_steps(records))}
|
||||
{results(recs, finder=True)}
|
||||
</div>
|
||||
</section>"""
|
||||
@@ -0,0 +1,227 @@
|
||||
"""The shared page frame: <head>, header and navigation, footer.
|
||||
|
||||
To add a page (see also docs in pages.py):
|
||||
|
||||
from olt.layout import layout, page_head, write_page
|
||||
from olt.markup import esc
|
||||
|
||||
body = page_head("Regions", kicker="Browse", lede="Trails by state, province and territory.")
|
||||
body += f'<div class="container prose">...{esc(some_text)}...</div>'
|
||||
html = layout("Regions", body, path="/regions/", description="Long trails by region.")
|
||||
write_page(out_dir, "/regions/", html)
|
||||
|
||||
`path` is the page's own site path; it sets the canonical link (when
|
||||
site.toml has base_url) and marks the current item in the navigation.
|
||||
Everything else on the page comes from style.css and app.js; no inline
|
||||
scripts or styles (the Content-Security-Policy forbids them).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
from . import site as site_settings
|
||||
from .markup import Markup, attrs, esc, json_block
|
||||
|
||||
NAV = (
|
||||
("Trails", "/"),
|
||||
("Regions", "/regions/"),
|
||||
("Routes", "/routes/"),
|
||||
("Sources", "/sources/"),
|
||||
("Logos", "/logos/"),
|
||||
("About", "/about/"),
|
||||
("Data", "/data/"),
|
||||
)
|
||||
|
||||
FONT_PRELOADS = (
|
||||
"/assets/fonts/source-serif-4-latin.woff2",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-400-latin.woff2",
|
||||
)
|
||||
MAPLIBRE_CSS = "/assets/vendor/maplibre-gl/maplibre-gl.css"
|
||||
MAPLIBRE_JS = "/assets/vendor/maplibre-gl/maplibre-gl.js"
|
||||
|
||||
|
||||
def _current(path, href):
|
||||
"""True when the nav item href is the section the page at path belongs to."""
|
||||
if href == "/":
|
||||
return path == "/" or path.startswith("/trails/")
|
||||
return path.startswith(href)
|
||||
|
||||
|
||||
def header(path, site):
|
||||
items = "".join(
|
||||
f'<li><a href="{esc(href)}"{attrs(aria_current="page" if path == href else ("true" if _current(path, href) else None))}>'
|
||||
f"{esc(text)}</a></li>"
|
||||
for text, href in NAV)
|
||||
return Markup(f"""<header class="site-header">
|
||||
<div class="container site-header__inner">
|
||||
<a class="wordmark" href="/"><span class="wordmark__blaze" aria-hidden="true"></span>{esc(site.name)}</a>
|
||||
<nav aria-label="Main"><ul class="nav">{items}</ul></nav>
|
||||
</div>
|
||||
</header>""")
|
||||
|
||||
|
||||
def footer(site):
|
||||
report = (f'<li><a href="{esc(site.issues_url)}">Report an error in a record</a></li>'
|
||||
if site.issues_url else "")
|
||||
return Markup(f"""<footer class="site-footer">
|
||||
<div class="container site-footer__grid">
|
||||
<div class="site-footer__about">
|
||||
<a class="wordmark" href="/"><span class="wordmark__blaze" aria-hidden="true"></span>{esc(site.name)}</a>
|
||||
<p>A dataset, not a navigation product: lines vary in quality, some trails are unfinished, and some records have no line at all. Check a trail’s own record before using its line.</p>
|
||||
<p>The records are public domain (CC0-1.0). Each line keeps the terms of its source, named on its page. Lines from OpenStreetMap are © OpenStreetMap contributors, under the ODbL. Logos belong to their holders and are shown only to identify each trail.</p>
|
||||
</div>
|
||||
<nav aria-labelledby="footer-data">
|
||||
<h2 id="footer-data">Data</h2>
|
||||
<ul>
|
||||
<li><a href="/data/">About the data and downloads</a></li>
|
||||
<li><a href="/data/trails.csv">trails.csv</a>: one row per trail</li>
|
||||
<li><a href="/data/index.geojson">index.geojson</a>: every line, simplified</li>
|
||||
<li><a href="/sources/">Sources and their terms</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<nav aria-labelledby="footer-project">
|
||||
<h2 id="footer-project">Project</h2>
|
||||
<ul>
|
||||
<li><a href="/about/">About {esc(site.name)}</a></li>
|
||||
<li><a href="/logos/">Logos and removal requests</a></li>
|
||||
{report}
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="site-footer__prefs">
|
||||
<fieldset class="field">
|
||||
<legend>Theme</legend>
|
||||
<div class="seg">
|
||||
<label><input type="radio" name="theme" value="auto" checked><span>Auto</span></label>
|
||||
<label><input type="radio" name="theme" value="light"><span>Light</span></label>
|
||||
<label><input type="radio" name="theme" value="dark"><span>Dark</span></label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="field">
|
||||
<legend>Lengths</legend>
|
||||
<div class="seg">
|
||||
<label><input type="radio" name="units" value="km" checked><span>km first</span></label>
|
||||
<label><input type="radio" name="units" value="mi"><span>miles first</span></label>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
</div>
|
||||
<div class="site-footer__base">
|
||||
<div class="container">Base maps: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.</div>
|
||||
</div>
|
||||
</footer>""")
|
||||
|
||||
|
||||
def _ld_json_block(obj):
|
||||
text = json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||
text = text.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
|
||||
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"):
|
||||
"""Return a complete HTML document.
|
||||
|
||||
title the page's own title ("Arizona National Scenic Trail"); the site
|
||||
name is appended. Empty for the home page: "<name>: <tagline>".
|
||||
body the page content (HTML, Markup or str), placed inside <main>.
|
||||
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]).
|
||||
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.
|
||||
"""
|
||||
site = site or site_settings.load()
|
||||
full_title = f"{title} · {site.name}" if title else f"{site.name}: {site.tagline}"
|
||||
description = description or site.tagline
|
||||
canonical = site.canonical(path)
|
||||
head = [
|
||||
'<meta charset="utf-8">',
|
||||
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
||||
f"<title>{esc(full_title)}</title>",
|
||||
f'<meta name="description" content="{esc(description)}">',
|
||||
]
|
||||
if canonical:
|
||||
head.append(f'<link rel="canonical" href="{esc(canonical)}">')
|
||||
head += [
|
||||
f'<meta property="og:title" content="{esc(full_title)}">',
|
||||
f'<meta property="og:description" content="{esc(description)}">',
|
||||
f'<meta property="og:type" content="{esc(og_type)}">',
|
||||
f'<meta property="og:site_name" content="{esc(site.name)}">',
|
||||
'<meta name="twitter:card" content="summary">',
|
||||
f'<meta name="twitter:title" content="{esc(full_title)}">',
|
||||
f'<meta name="twitter:description" content="{esc(description)}">',
|
||||
]
|
||||
if canonical:
|
||||
head.append(f'<meta property="og:url" content="{esc(canonical)}">')
|
||||
head.append(f'<meta property="og:image" content="{esc(site.canonical("/assets/favicon.svg"))}">')
|
||||
head.append(f'<meta name="twitter:image" content="{esc(site.canonical("/assets/favicon.svg"))}">')
|
||||
if jsonld is not None:
|
||||
head.append(str(_ld_json_block(jsonld)))
|
||||
head += [
|
||||
'<meta name="color-scheme" content="light dark">',
|
||||
'<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml">',
|
||||
]
|
||||
head += [f'<link rel="preload" href="{f}" as="font" type="font/woff2" crossorigin>' for f in FONT_PRELOADS]
|
||||
if maps:
|
||||
head.append(f'<link rel="stylesheet" href="{MAPLIBRE_CSS}">')
|
||||
head += [
|
||||
'<link rel="stylesheet" href="/assets/style.css">',
|
||||
# Sets the theme and unit preference before first paint (no inline scripts allowed).
|
||||
'<script src="/assets/prefs.js"></script>',
|
||||
]
|
||||
# app.js first: deferred scripts run in order, and the finder and the rest of the
|
||||
# page must not wait for MapLibre (app.js starts the maps when MapLibre arrives).
|
||||
head.append('<script src="/assets/app.js" defer></script>')
|
||||
if maps:
|
||||
head.append(f'<script src="{MAPLIBRE_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>
|
||||
<html lang="en">
|
||||
<head>
|
||||
{chr(10).join(head)}
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main">Skip to content</a>
|
||||
{header(path, site)}
|
||||
<main id="main">
|
||||
{body}
|
||||
</main>
|
||||
{footer(site)}
|
||||
{data_block}
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def page_head(title, *, kicker="", lede="", crumbs=()):
|
||||
"""A plain page heading block: breadcrumb, kicker, <h1>, lede. For simple pages.
|
||||
|
||||
crumbs is a sequence of (text, href) pairs leading to this page.
|
||||
"""
|
||||
crumb_html = ""
|
||||
if crumbs:
|
||||
items = "".join(f'<li><a href="{esc(h)}">{esc(t)}</a></li>' for t, h in crumbs)
|
||||
crumb_html = (f'<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{items}'
|
||||
f'<li aria-current="page">{esc(title)}</li></ol></nav>')
|
||||
kicker_html = f'<p class="kicker">{esc(kicker)}</p>' if kicker else ""
|
||||
lede_html = f'<p class="page-head__lede">{esc(lede)}</p>' if lede else ""
|
||||
return Markup(f"""<div class="page-head">
|
||||
<div class="container">
|
||||
{crumb_html}
|
||||
<header class="titleblock">
|
||||
<div class="titleblock__text">{kicker_html}<h1>{esc(title)}</h1>{lede_html}</div>
|
||||
</header>
|
||||
</div>
|
||||
</div>""")
|
||||
|
||||
|
||||
def write_page(out_dir, path, document):
|
||||
"""Write a page for a site path: "/" -> index.html, "/a/b/" -> a/b/index.html, "/404.html" -> 404.html."""
|
||||
rel = path.lstrip("/")
|
||||
if not rel or rel.endswith("/"):
|
||||
rel += "index.html"
|
||||
dest = os.path.join(out_dir, *rel.split("/"))
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
with open(dest, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(document)
|
||||
return dest
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Small HTML helpers: escaping, attributes, joining. Standard library only.
|
||||
|
||||
Write page templates as f-strings and pass every value that comes from data
|
||||
through esc() (text and attribute values alike). Strings that are already HTML
|
||||
are Markup; esc() leaves them alone, so helpers can return Markup and be
|
||||
dropped into other templates without double escaping.
|
||||
"""
|
||||
import html
|
||||
import json
|
||||
|
||||
|
||||
class Markup(str):
|
||||
"""A string that is already HTML and must not be escaped again."""
|
||||
|
||||
|
||||
def esc(value):
|
||||
"""Escape text for HTML text or a double-quoted attribute value."""
|
||||
if isinstance(value, Markup):
|
||||
return value
|
||||
if value is None:
|
||||
return Markup("")
|
||||
return Markup(html.escape(str(value), quote=True))
|
||||
|
||||
|
||||
def attrs(**kw):
|
||||
"""Attribute string: attrs(class_="a", data_id="x", hidden=True) -> ' class="a" data-id="x" hidden'.
|
||||
|
||||
A trailing underscore is dropped (class_ -> class) and other underscores
|
||||
become hyphens (aria_label -> aria-label). None and False are left out.
|
||||
"""
|
||||
out = []
|
||||
for key, value in kw.items():
|
||||
if value is None or value is False:
|
||||
continue
|
||||
name = key.rstrip("_").replace("_", "-")
|
||||
out.append(f" {name}" if value is True else f' {name}="{esc(value)}"')
|
||||
return Markup("".join(out))
|
||||
|
||||
|
||||
def join(items, sep=""):
|
||||
"""Join pieces of HTML; plain strings among them are escaped."""
|
||||
return Markup(esc(sep).join(esc(i) for i in items if i not in (None, "")))
|
||||
|
||||
|
||||
def link(href, text, **kw):
|
||||
"""<a href=...>text</a>, with text escaped unless it is Markup."""
|
||||
return Markup(f"<a{attrs(href=href, **kw)}>{esc(text)}</a>")
|
||||
|
||||
|
||||
def json_block(obj, id_):
|
||||
"""A non-executed <script type="application/json"> block (allowed by the site's CSP)."""
|
||||
text = json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||
text = text.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
|
||||
return Markup(f'<script type="application/json" id="{esc(id_)}">{text}</script>')
|
||||
@@ -0,0 +1,710 @@
|
||||
"""Markdown-to-HTML renderer for the site's own documents.
|
||||
|
||||
Covers what README.md, SOURCES.md, NOTICE.md, CONTRIBUTING.md, CHANGELOG.md
|
||||
and docs/schema.md actually use, and little more.
|
||||
|
||||
Supported: ATX headings, paragraphs, unordered (``-``) and ordered (``1.``)
|
||||
lists including nested lists and multi-line items, pipe tables with an
|
||||
alignment row (``---``, ``---:``, ``:---:``), fenced code blocks with an
|
||||
optional language, inline code, bold, italic, ``[text](url)`` links (also in
|
||||
table cells; destinations may hold balanced parentheses or underscores), bare
|
||||
``http(s)://`` URLs and ``<http(s)://...>`` autolinks, ``>`` block quotes,
|
||||
``---``/``***``/``___`` horizontal rules, backslash escapes, and
|
||||
``<!-- ... -->`` comments, which are dropped from the output.
|
||||
|
||||
Not supported: setext headings, reference-style links (a title after an
|
||||
inline link's destination is accepted and dropped), images, footnotes,
|
||||
strikethrough, task lists, indented code blocks, raw HTML passthrough
|
||||
(anything but comments is escaped, never passed through), and emphasis
|
||||
inside code spans or link destinations.
|
||||
"""
|
||||
|
||||
import html as _html
|
||||
import re
|
||||
|
||||
_HEADING_RE = re.compile(r"^(#{1,6})[ \t]*(.*?)[ \t]*$")
|
||||
_CLOSING_HASHES_RE = re.compile(r" +#+$")
|
||||
_LIST_RE = re.compile(r"^([ ]*)([-+*]|\d+[.)])(?:[ \t]+|$)(.*)$")
|
||||
_ALIGN_RE = re.compile(r"^:?-+:?$")
|
||||
_TAG_RE = re.compile(r"<[^>]*>")
|
||||
_LANG_RE = re.compile(r"^[A-Za-z0-9_-]+$")
|
||||
_AUTOLINK_RE = re.compile(r"^<(https?://[^<>\s]+)>")
|
||||
|
||||
_PUNCT = set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
|
||||
|
||||
|
||||
def render(text, *, heading_offset=0, link_rewrite=None):
|
||||
"""Render Markdown to an HTML fragment (no <html>/<body>).
|
||||
|
||||
``heading_offset`` shifts every heading down (``#`` becomes ``<h2>``
|
||||
with ``heading_offset=1``), capped at ``h6``. ``link_rewrite`` is an
|
||||
optional function called with each link's href, returning the href
|
||||
to use in the output, or None to drop the link and keep only its text.
|
||||
"""
|
||||
slugs = {}
|
||||
lines = _strip_comments(text).split("\n")
|
||||
return "\n".join(_blocks(lines, heading_offset, link_rewrite, slugs))
|
||||
|
||||
|
||||
def headings(text):
|
||||
"""Return ``(level, plain text, slug id)`` for each heading, in order.
|
||||
|
||||
The slug is the same id ``render`` puts on the heading element. Slugs
|
||||
are lower-case and hyphenated, and repeats get ``-2``, ``-3`` suffixes.
|
||||
"""
|
||||
found = []
|
||||
slugs = {}
|
||||
in_fence = False
|
||||
for line in _strip_comments(text).split("\n"):
|
||||
if _fence_open(line) is not None or _fence_close(line):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
parsed = _parse_heading(line)
|
||||
if parsed is None:
|
||||
continue
|
||||
level, raw = parsed
|
||||
plain = _plain(raw)
|
||||
found.append((level, plain, _slugify(plain, slugs)))
|
||||
return found
|
||||
|
||||
|
||||
def split_sections(text, level=2):
|
||||
"""Split Markdown into ``(heading text, Markdown body)`` sections.
|
||||
|
||||
A new section starts at each ATX heading with exactly ``level``
|
||||
hashes; its body is the raw Markdown under it, up to the next heading
|
||||
of that level or shallower (deeper headings stay in the body). Text
|
||||
before the first such heading is not part of any section.
|
||||
"""
|
||||
if not 1 <= level <= 6:
|
||||
raise ValueError("level must be 1..6")
|
||||
sections = []
|
||||
title = None
|
||||
body = []
|
||||
in_fence = False
|
||||
for line in _strip_comments(text).split("\n"):
|
||||
if _fence_open(line) is not None or _fence_close(line):
|
||||
in_fence = not in_fence
|
||||
if title is not None:
|
||||
body.append(line)
|
||||
continue
|
||||
parsed = _parse_heading(line) if not in_fence else None
|
||||
if parsed is not None and parsed[0] <= level:
|
||||
if title is not None:
|
||||
sections.append((title, _trim(body)))
|
||||
if parsed[0] == level:
|
||||
title = _plain(parsed[1])
|
||||
body = []
|
||||
else:
|
||||
title = None
|
||||
body = []
|
||||
elif title is not None:
|
||||
body.append(line)
|
||||
if title is not None:
|
||||
sections.append((title, _trim(body)))
|
||||
return sections
|
||||
|
||||
|
||||
def _trim(lines):
|
||||
while lines and not lines[0].strip():
|
||||
del lines[0]
|
||||
while lines and not lines[-1].strip():
|
||||
del lines[-1]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Block layer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _blocks(lines, offset, link_rewrite, slugs):
|
||||
out = []
|
||||
i = 0
|
||||
n = len(lines)
|
||||
while i < n:
|
||||
line = lines[i]
|
||||
if not line.strip():
|
||||
i += 1
|
||||
continue
|
||||
if _fence_open(line) is not None:
|
||||
html, i = _take_fence(lines, i)
|
||||
out.append(html)
|
||||
elif _parse_heading(line) is not None:
|
||||
level, raw = _parse_heading(line)
|
||||
plain = _plain(raw)
|
||||
tag = min(6, level + offset)
|
||||
slug = _slugify(plain, slugs)
|
||||
out.append(f"<h{tag} id=\"{slug}\">"
|
||||
f"{_inline(raw, link_rewrite)}</h{tag}>")
|
||||
i += 1
|
||||
elif _is_hr(line):
|
||||
out.append("<hr>")
|
||||
i += 1
|
||||
elif _parse_quote(line) is not None:
|
||||
quoted = []
|
||||
while i < n and _parse_quote(lines[i]) is not None:
|
||||
quoted.append(_parse_quote(lines[i]))
|
||||
i += 1
|
||||
inner = _blocks(quoted, offset, link_rewrite, slugs)
|
||||
if inner:
|
||||
out.append("<blockquote>\n" + "\n".join(inner)
|
||||
+ "\n</blockquote>")
|
||||
else:
|
||||
out.append("<blockquote>\n</blockquote>")
|
||||
elif _is_list_start(line):
|
||||
html, i = _parse_list(lines, i, offset, link_rewrite, slugs)
|
||||
out.append(html)
|
||||
elif _table_at(lines, i) is not None:
|
||||
html, i = _take_table(lines, i, link_rewrite)
|
||||
out.append(html)
|
||||
else:
|
||||
buf = [line]
|
||||
i += 1
|
||||
while i < n and not _starts_block(lines, i):
|
||||
buf.append(lines[i])
|
||||
i += 1
|
||||
out.append("<p>" + _inline("\n".join(buf).strip(),
|
||||
link_rewrite) + "</p>")
|
||||
return out
|
||||
|
||||
|
||||
def _starts_block(lines, i):
|
||||
line = lines[i]
|
||||
if not line.strip():
|
||||
return True
|
||||
if _fence_open(line) is not None:
|
||||
return True
|
||||
if _parse_heading(line) is not None:
|
||||
return True
|
||||
if _is_hr(line):
|
||||
return True
|
||||
if _parse_quote(line) is not None:
|
||||
return True
|
||||
if _is_list_start(line):
|
||||
return True
|
||||
if _table_at(lines, i) is not None:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_heading(line):
|
||||
"""Return ``(level, raw text)`` for an ATX heading, else None."""
|
||||
body = line.lstrip(" ")
|
||||
if len(line) - len(body) > 3 or not body.startswith("#"):
|
||||
return None
|
||||
match = _HEADING_RE.match(body)
|
||||
if match is None:
|
||||
return None
|
||||
hashes, rest = match.group(1), match.group(2)
|
||||
if body[len(hashes):len(hashes) + 1] not in ("", " ", "\t"):
|
||||
return None
|
||||
rest = _CLOSING_HASHES_RE.sub("", rest).strip()
|
||||
return (len(hashes), rest)
|
||||
|
||||
|
||||
def _fence_open(line):
|
||||
"""Return the info string for a fence opener, else None."""
|
||||
body = line.lstrip(" ")
|
||||
if len(line) - len(body) > 3 or not body.startswith("```"):
|
||||
return None
|
||||
if body[3:4] == "`":
|
||||
return None
|
||||
return body[3:].strip()
|
||||
|
||||
|
||||
def _fence_close(line):
|
||||
stripped = line.strip()
|
||||
return (stripped.startswith("```")
|
||||
and all(ch in " \t" for ch in stripped[3:]))
|
||||
|
||||
|
||||
def _take_fence(lines, i):
|
||||
info = _fence_open(lines[i])
|
||||
lang = info.split()[0] if info.split() else ""
|
||||
buf = []
|
||||
i += 1
|
||||
while i < len(lines) and not _fence_close(lines[i]):
|
||||
buf.append(lines[i])
|
||||
i += 1
|
||||
if i < len(lines):
|
||||
i += 1
|
||||
if lang and _LANG_RE.match(lang):
|
||||
open_tag = f'<pre><code class="language-{lang}">'
|
||||
else:
|
||||
open_tag = "<pre><code>"
|
||||
return open_tag + _html.escape("\n".join(buf)) + "</code></pre>", i
|
||||
|
||||
|
||||
def _is_hr(line):
|
||||
stripped = line.strip()
|
||||
if len(stripped) < 3 or stripped[0] not in "*-_":
|
||||
return False
|
||||
char = stripped[0]
|
||||
return (stripped.count(char) >= 3
|
||||
and all(ch in (char, " ", "\t") for ch in stripped))
|
||||
|
||||
|
||||
def _parse_quote(line):
|
||||
"""Return the line's quote content, else None."""
|
||||
body = line.lstrip(" ")
|
||||
if len(line) - len(body) > 3 or not body.startswith(">"):
|
||||
return None
|
||||
rest = body[1:]
|
||||
if rest.startswith((" ", "\t")):
|
||||
rest = rest[1:]
|
||||
return rest
|
||||
|
||||
|
||||
def _is_list_start(line):
|
||||
match = _LIST_RE.match(line)
|
||||
return match is not None and len(match.group(1)) <= 3
|
||||
|
||||
|
||||
def _parse_list(lines, i, offset, link_rewrite, slugs):
|
||||
first = _LIST_RE.match(lines[i])
|
||||
base = len(first.group(1))
|
||||
ordered = first.group(2)[0].isdigit()
|
||||
start = int(first.group(2)[:-1]) if ordered else 1
|
||||
items = []
|
||||
loose = False
|
||||
n = len(lines)
|
||||
while i < n:
|
||||
match = _LIST_RE.match(lines[i])
|
||||
if (match is None or len(match.group(1)) != base
|
||||
or (match.group(2)[0].isdigit() != ordered)):
|
||||
break
|
||||
content_indent = base + len(match.group(2)) + 1
|
||||
item = [match.group(3)]
|
||||
i += 1
|
||||
while i < n:
|
||||
line = lines[i]
|
||||
if not line.strip():
|
||||
end = i
|
||||
while end < n and not lines[end].strip():
|
||||
end += 1
|
||||
if end >= n:
|
||||
i = end
|
||||
break
|
||||
peek = _LIST_RE.match(lines[end])
|
||||
peek_indent = len(lines[end]) - len(lines[end].lstrip(" "))
|
||||
same_item = peek is not None and peek.group(2)[0].isdigit() == ordered and peek_indent == base
|
||||
if same_item or peek_indent >= content_indent:
|
||||
loose = True
|
||||
item.append("")
|
||||
i = end
|
||||
else:
|
||||
break
|
||||
continue
|
||||
inner = _LIST_RE.match(line)
|
||||
indent = len(line) - len(line.lstrip(" "))
|
||||
if (inner is not None and indent == base
|
||||
and inner.group(2)[0].isdigit() == ordered):
|
||||
break
|
||||
if indent >= content_indent:
|
||||
item.append(line[content_indent:])
|
||||
i += 1
|
||||
else:
|
||||
break
|
||||
while item and not item[-1].strip():
|
||||
item.pop()
|
||||
items.append(item)
|
||||
rendered = []
|
||||
for item in items:
|
||||
sub = _blocks(item, offset, link_rewrite, slugs)
|
||||
if (not loose and sub and sub[0].startswith("<p>")
|
||||
and sub[0].endswith("</p>")):
|
||||
sub = [sub[0][len("<p>"):-len("</p>")]] + sub[1:]
|
||||
rendered.append("<li>" + "\n".join(sub) + "</li>" if sub else "<li></li>")
|
||||
if ordered and start != 1:
|
||||
open_tag, close_tag = f'<ol start="{start}">', "</ol>"
|
||||
elif ordered:
|
||||
open_tag, close_tag = "<ol>", "</ol>"
|
||||
else:
|
||||
open_tag, close_tag = "<ul>", "</ul>"
|
||||
return open_tag + "\n" + "\n".join(rendered) + "\n" + close_tag, i
|
||||
|
||||
|
||||
def _split_cells(line):
|
||||
"""Split a table row into cell segment lists.
|
||||
|
||||
Each cell is a list of ``(is_code, text)`` segments. Pipes inside
|
||||
code spans or escaped as ``\\|`` never split the cell.
|
||||
"""
|
||||
text = line.strip()
|
||||
if text.startswith("|"):
|
||||
text = text[1:]
|
||||
if text.endswith("|") and not text.endswith("\\|"):
|
||||
text = text[:-1]
|
||||
cells = []
|
||||
current = []
|
||||
for is_code, chunk in _split_code(text):
|
||||
if is_code:
|
||||
current.append((True, chunk))
|
||||
else:
|
||||
pieces = re.split(r"(?<!\\)\|", chunk)
|
||||
current.append((False, pieces[0]))
|
||||
for piece in pieces[1:]:
|
||||
cells.append(current)
|
||||
current = [(False, piece)]
|
||||
cells.append(current)
|
||||
for cell in cells:
|
||||
if cell and not cell[0][0]:
|
||||
cell[0] = (False, cell[0][1].lstrip(" \t"))
|
||||
if cell and not cell[-1][0]:
|
||||
cell[-1] = (False, cell[-1][1].rstrip(" \t"))
|
||||
return cells
|
||||
|
||||
|
||||
def _render_cell(cell, link_rewrite):
|
||||
parts = []
|
||||
for is_code, chunk in cell:
|
||||
if is_code:
|
||||
parts.append("<code>" + _html.escape(chunk) + "</code>")
|
||||
else:
|
||||
parts.append(_inline_raw(chunk, link_rewrite))
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _align(cell):
|
||||
text = cell.strip()
|
||||
if text.startswith(":") and text.endswith(":") and len(text) > 2:
|
||||
return "center"
|
||||
if text.endswith(":"):
|
||||
return "right"
|
||||
return "left"
|
||||
|
||||
|
||||
def _table_at(lines, i):
|
||||
"""Return the alignment row's cells if a table starts here."""
|
||||
if "|" not in lines[i] or i + 1 >= len(lines):
|
||||
return None
|
||||
cells = _split_cells(lines[i + 1])
|
||||
if not cells:
|
||||
return None
|
||||
raws = []
|
||||
for cell in cells:
|
||||
raws.append("".join(chunk for _, chunk in cell))
|
||||
if any(not _ALIGN_RE.match(raw.strip()) for raw in raws):
|
||||
return None
|
||||
return raws
|
||||
|
||||
|
||||
def _take_table(lines, i, link_rewrite):
|
||||
header = _split_cells(lines[i])
|
||||
aligns = [_align("".join(chunk for _, chunk in cell))
|
||||
for cell in _split_cells(lines[i + 1])]
|
||||
width = max(len(header), len(aligns))
|
||||
while len(header) < width:
|
||||
header.append([(False, "")])
|
||||
while len(aligns) < width:
|
||||
aligns.append("left")
|
||||
|
||||
def row(cells, tag):
|
||||
out = []
|
||||
scope = ' scope="col"' if tag == "th" else ""
|
||||
for pos in range(width):
|
||||
cell = cells[pos] if pos < len(cells) else [(False, "")]
|
||||
cls = ' class="num"' if aligns[pos] == "right" else ""
|
||||
out.append(f"<{tag}{scope}{cls}>" + _render_cell(cell, link_rewrite)
|
||||
+ f"</{tag}>")
|
||||
return "<tr>" + "".join(out) + "</tr>"
|
||||
|
||||
head = row(header, "th")
|
||||
body_rows = []
|
||||
i += 2
|
||||
while i < len(lines) and lines[i].strip() and "|" in lines[i]:
|
||||
body_rows.append(row(_split_cells(lines[i]), "td"))
|
||||
i += 1
|
||||
html = "<table>\n<thead>\n" + head + "\n</thead>"
|
||||
if body_rows:
|
||||
html += "\n<tbody>\n" + "\n".join(body_rows) + "\n</tbody>"
|
||||
return html + "\n</table>", i
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Comments, slugs, plain text
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _strip_comments(text):
|
||||
"""Drop ``<!-- ... -->`` spans; fenced code blocks are left alone."""
|
||||
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
||||
out = []
|
||||
in_fence = False
|
||||
in_comment = False
|
||||
for line in text.split("\n"):
|
||||
if not in_comment and (_fence_open(line) is not None
|
||||
or _fence_close(line)):
|
||||
in_fence = not in_fence
|
||||
out.append(line)
|
||||
continue
|
||||
if in_fence:
|
||||
out.append(line)
|
||||
continue
|
||||
line, in_comment = _strip_line_comment(line, in_comment)
|
||||
out.append(line)
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _strip_line_comment(line, in_comment):
|
||||
if in_comment:
|
||||
end = line.find("-->")
|
||||
if end < 0:
|
||||
return "", True
|
||||
line = line[end + 3:]
|
||||
in_comment = False
|
||||
while True:
|
||||
start = line.find("<!--")
|
||||
if start < 0:
|
||||
return line, False
|
||||
end = line.find("-->", start + 4)
|
||||
if end < 0:
|
||||
return line[:start], True
|
||||
line = line[:start] + line[end + 3:]
|
||||
|
||||
|
||||
def _plain(raw):
|
||||
"""Inline formatting stripped to plain text (for headings)."""
|
||||
return _html.unescape(_TAG_RE.sub("", _inline(raw, None)))
|
||||
|
||||
|
||||
def _slugify(plain, slugs):
|
||||
base = re.sub(r"[^a-z0-9]+", "-", plain.lower()).strip("-")
|
||||
if not base:
|
||||
base = "section"
|
||||
count = slugs.get(base, 0) + 1
|
||||
slugs[base] = count
|
||||
return base if count == 1 else f"{base}-{count}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Inline layer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _inline(text, link_rewrite):
|
||||
parts = []
|
||||
for is_code, chunk in _split_code(text):
|
||||
if is_code:
|
||||
code = chunk
|
||||
if len(code) > 2 and code[0] in " \t" and code[-1] in " \t" and code.strip(" \t"):
|
||||
code = code[1:-1]
|
||||
parts.append("<code>" + _html.escape(code) + "</code>")
|
||||
else:
|
||||
parts.append(_inline_raw(chunk, link_rewrite))
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _split_code(text):
|
||||
"""Split text into ``(is_code, chunk)`` parts at backtick spans."""
|
||||
parts = []
|
||||
buf = []
|
||||
i = 0
|
||||
n = len(text)
|
||||
while i < n:
|
||||
if text[i] != "`":
|
||||
buf.append(text[i])
|
||||
i += 1
|
||||
continue
|
||||
end = i
|
||||
while end < n and text[end] == "`":
|
||||
end += 1
|
||||
run = end - i
|
||||
close = _find_close(text, end, run)
|
||||
if close < 0:
|
||||
buf.append(text[i:end])
|
||||
i = end
|
||||
else:
|
||||
if buf:
|
||||
parts.append((False, "".join(buf)))
|
||||
buf = []
|
||||
parts.append((True, text[end:close]))
|
||||
i = close + run
|
||||
if buf:
|
||||
parts.append((False, "".join(buf)))
|
||||
return parts
|
||||
|
||||
|
||||
def _find_close(text, start, run):
|
||||
tick = "`" * run
|
||||
pos = text.find(tick, start)
|
||||
while pos >= 0:
|
||||
prev_is_tick = pos > 0 and text[pos - 1] == "`"
|
||||
next_is_tick = pos + run < len(text) and text[pos + run] == "`"
|
||||
if not prev_is_tick and not next_is_tick:
|
||||
return pos
|
||||
pos = text.find(tick, pos + 1)
|
||||
return -1
|
||||
|
||||
|
||||
def _inline_raw(text, link_rewrite):
|
||||
out = []
|
||||
i = 0
|
||||
n = len(text)
|
||||
while i < n:
|
||||
char = text[i]
|
||||
if char == "\\" and i + 1 < n and text[i + 1] in _PUNCT:
|
||||
out.append(_html.escape(text[i + 1]))
|
||||
i += 2
|
||||
elif char == "[":
|
||||
html, i = _parse_link(text, i, link_rewrite)
|
||||
out.append(html)
|
||||
elif char == "<":
|
||||
html, i = _parse_angle(text, i, link_rewrite)
|
||||
out.append(html)
|
||||
elif ((text.startswith("http://", i) or text.startswith("https://", i))
|
||||
and (i == 0 or text[i - 1] in " \t\n('\"")):
|
||||
html, i = _parse_bare(text, i, link_rewrite)
|
||||
out.append(html)
|
||||
elif char in "*_":
|
||||
html, i = _parse_emph(text, i, link_rewrite)
|
||||
out.append(html)
|
||||
elif char == "&":
|
||||
out.append("&")
|
||||
i += 1
|
||||
elif char == ">":
|
||||
out.append(">")
|
||||
i += 1
|
||||
else:
|
||||
out.append(_html.escape(char))
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _parse_link(text, i, link_rewrite):
|
||||
"""Parse ``[label](destination)`` at ``text[i] == '['``."""
|
||||
close = text.find("]", i + 1)
|
||||
if close < 0 or close + 1 >= len(text) or text[close + 1] != "(":
|
||||
return "[", i + 1
|
||||
pos = close + 2
|
||||
while pos < len(text) and text[pos] in " \t":
|
||||
pos += 1
|
||||
if pos < len(text) and text[pos] == "<":
|
||||
end = text.find(">", pos + 1)
|
||||
if end < 0:
|
||||
return "[", i + 1
|
||||
dest, pos = text[pos + 1:end], end + 1
|
||||
else:
|
||||
start = pos
|
||||
depth = 0
|
||||
while pos < len(text):
|
||||
char = text[pos]
|
||||
if char == "(":
|
||||
depth += 1
|
||||
elif char == ")":
|
||||
if depth == 0:
|
||||
break
|
||||
depth -= 1
|
||||
elif char in " \t\n" and depth == 0:
|
||||
break
|
||||
pos += 1
|
||||
dest = text[start:pos]
|
||||
end = pos
|
||||
while end < len(text) and text[end] in " \t":
|
||||
end += 1
|
||||
if end < len(text) and text[end] in "\"'(":
|
||||
quote = ")" if text[end] == "(" else text[end]
|
||||
title_end = text.find(quote, end + 1)
|
||||
if title_end < 0:
|
||||
return "[", i + 1
|
||||
end = title_end + 1
|
||||
if end >= len(text) or text[end] != ")":
|
||||
return "[", i + 1
|
||||
pos = end
|
||||
if pos >= len(text) or text[pos] != ")":
|
||||
return "[", i + 1
|
||||
href = dest.strip()
|
||||
if not href:
|
||||
return "[", i + 1
|
||||
if link_rewrite is not None:
|
||||
href = link_rewrite(href)
|
||||
inner = _inline(text[i + 1:close], link_rewrite)
|
||||
if href is None:
|
||||
return inner, pos + 1
|
||||
return (f'<a href="{_html.escape(href, quote=True)}">{inner}</a>',
|
||||
pos + 1)
|
||||
|
||||
|
||||
def _parse_angle(text, i, link_rewrite):
|
||||
"""Parse ``<https://...>`` autolinks; anything else is escaped."""
|
||||
match = _AUTOLINK_RE.match(text[i:])
|
||||
if match is None:
|
||||
return "<", i + 1
|
||||
url = match.group(1)
|
||||
href = link_rewrite(url) if link_rewrite is not None else url
|
||||
return _anchor(href, url), i + match.end()
|
||||
|
||||
|
||||
def _parse_bare(text, i, link_rewrite):
|
||||
end = i
|
||||
while end < len(text) and text[end] not in " \t\n<>":
|
||||
end += 1
|
||||
url = text[i:end].rstrip(".,;:!?")
|
||||
while url.endswith(")") and url.count("(") < url.count(")"):
|
||||
url = url[:-1]
|
||||
href = link_rewrite(url) if link_rewrite is not None else url
|
||||
return _anchor(href, url), i + len(url)
|
||||
|
||||
|
||||
def _anchor(href, text):
|
||||
"""``<a>`` around escaped text, or the text alone when href is None."""
|
||||
if href is None:
|
||||
return _html.escape(text)
|
||||
return (f'<a href="{_html.escape(href, quote=True)}">'
|
||||
f"{_html.escape(text)}</a>")
|
||||
|
||||
|
||||
def _can_open(char, prev, nxt):
|
||||
if not nxt or nxt in " \t\n":
|
||||
return False
|
||||
return not (char == "_" and prev.isalnum() and nxt.isalnum())
|
||||
|
||||
|
||||
def _can_close(char, prev, nxt):
|
||||
if not prev or prev in " \t\n":
|
||||
return False
|
||||
return not (char == "_" and prev.isalnum() and nxt.isalnum())
|
||||
|
||||
|
||||
def _find_closer(text, pos, char, run_len):
|
||||
i = pos
|
||||
n = len(text)
|
||||
while i < n:
|
||||
if text[i] != char:
|
||||
i += 1
|
||||
continue
|
||||
end = i
|
||||
while end < n and text[end] == char:
|
||||
end += 1
|
||||
run = end - i
|
||||
if run >= run_len and (run_len == 2 or run == 1):
|
||||
prev = text[i - 1] if i > 0 else ""
|
||||
nxt = text[end] if end < n else ""
|
||||
if _can_close(char, prev, nxt):
|
||||
return i
|
||||
i = end
|
||||
return -1
|
||||
|
||||
|
||||
def _parse_emph(text, i, link_rewrite):
|
||||
"""Parse ``**bold**`` or ``*italic*`` at a ``*``/``_`` run."""
|
||||
char = text[i]
|
||||
end = i
|
||||
while end < len(text) and text[end] == char:
|
||||
end += 1
|
||||
run = end - i
|
||||
prev = text[i - 1] if i > 0 else ""
|
||||
for run_len, tag in ((2, "strong"), (1, "em")) if run >= 2 else ((1, "em"),):
|
||||
if run_len == 2 and run < 2:
|
||||
continue
|
||||
nxt = text[i + run_len] if i + run_len < len(text) else ""
|
||||
if not _can_open(char, prev, nxt):
|
||||
continue
|
||||
close = _find_closer(text, i + run_len, char, run_len)
|
||||
if close < 0:
|
||||
continue
|
||||
inner = _inline_raw(text[i + run_len:close], link_rewrite)
|
||||
if not inner.strip():
|
||||
continue
|
||||
return f"<{tag}>{inner}</{tag}>", close + run_len
|
||||
return _html.escape(text[i:end]), end
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Render the site's HTML pages. Called by web/build.py after the data files are written.
|
||||
|
||||
render_site(records, out_dir, repo_root)
|
||||
|
||||
writes:
|
||||
/assets/... web/assets/ copied verbatim (style.css, app.js, fonts, vendor)
|
||||
/index.html home: overview map and the trail finder with every record
|
||||
/trails/<id>/index.html one page per record
|
||||
/trails/<id>/trail.toml the raw record; release.txt beside it where the trail has one
|
||||
/trails/<id>/shield-thumb.png the list-size copy of a PNG logo (olt/thumbs.py)
|
||||
/404.html not found
|
||||
|
||||
Adding a page elsewhere (regions, sources, ...): build its body as HTML,
|
||||
wrap it with olt.layout.layout() and write it with olt.layout.write_page().
|
||||
See the docstring of olt/layout.py.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from . import docs, home, layout, regions, seo, site as site_settings, thumbs, trail
|
||||
|
||||
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ASSETS_DIR = os.path.join(WEB_DIR, "assets")
|
||||
|
||||
|
||||
def copy_assets(out_dir, assets_dir=ASSETS_DIR):
|
||||
"""Copy web/assets/ to <out>/assets/, replacing what was there."""
|
||||
dest = os.path.join(out_dir, "assets")
|
||||
if os.path.isdir(dest):
|
||||
shutil.rmtree(dest)
|
||||
shutil.copytree(assets_dir, dest, ignore=shutil.ignore_patterns("README.md", ".*"))
|
||||
|
||||
|
||||
def copy_record_files(rec, out_dir, repo_root):
|
||||
"""Copy trail.toml (and release.txt where present) next to the trail page.
|
||||
|
||||
Also notes on the record what the page needs to know about those files and
|
||||
the map geometry: derived.release and derived.map_bbox.
|
||||
"""
|
||||
tdir = os.path.join(out_dir, "trails", rec["id"])
|
||||
os.makedirs(tdir, exist_ok=True)
|
||||
shutil.copyfile(os.path.join(repo_root, rec["id"], "trail.toml"), os.path.join(tdir, "trail.toml"))
|
||||
release = trail.release_path(repo_root, rec)
|
||||
rec["derived"]["release"] = bool(release)
|
||||
if release:
|
||||
shutil.copyfile(release, os.path.join(tdir, "release.txt"))
|
||||
map_json = os.path.join(tdir, "map.json")
|
||||
if os.path.isfile(map_json):
|
||||
with open(map_json, encoding="utf-8") as f:
|
||||
box = json.load(f).get("bbox")
|
||||
if box:
|
||||
rec["derived"]["map_bbox"] = box
|
||||
|
||||
|
||||
def not_found_page(site):
|
||||
body = layout.page_head("Page not found", kicker="404",
|
||||
lede="There is no page at this address. Search the trails and routes by name instead.")
|
||||
body += """<div class="container section">
|
||||
<form class="notfound-search" action="/" method="get" role="search">
|
||||
<label class="field__label" for="notfound-q">Search the trails and routes</label>
|
||||
<input class="input" id="notfound-q" name="q" type="search" placeholder="Name, abbreviation or creator" autocomplete="off" spellcheck="false">
|
||||
<button class="button button--primary" type="submit">Search</button>
|
||||
</form>
|
||||
<p class="prose"><a href="/">Find a trail</a> on the home page, or browse <a href="/regions/">by region</a>.</p>
|
||||
</div>"""
|
||||
return layout.layout("Page not found", body, path="/404.html", site=site)
|
||||
|
||||
|
||||
def render_site(records, out_dir, repo_root, site=None):
|
||||
"""Write every HTML page for the given records. Returns the number of pages written."""
|
||||
site = site or site_settings.load()
|
||||
copy_assets(out_dir)
|
||||
pages = 0
|
||||
for rec in records:
|
||||
# Read by common.name() wherever a page shows the record's name as text.
|
||||
rec["derived"]["name_lang"] = site.name_lang.get(rec["id"], "")
|
||||
for rec in records:
|
||||
copy_record_files(rec, out_dir, repo_root)
|
||||
thumbs.prepare(rec, out_dir, repo_root)
|
||||
title, description, body, needs_map = trail.render(rec, site)
|
||||
path = f"/trails/{rec['id']}/"
|
||||
layout.write_page(out_dir, path, layout.layout(title, body, path=path, description=description,
|
||||
maps=needs_map, site=site))
|
||||
pages += 1
|
||||
dataset = seo.dataset_jsonld(records, site)
|
||||
body = home.render(records, site)
|
||||
layout.write_page(out_dir, "/", layout.layout("", body, path="/", maps=True, site=site, jsonld=dataset))
|
||||
layout.write_page(out_dir, "/404.html", not_found_page(site))
|
||||
pages += 2
|
||||
|
||||
def add(path, title, description, body_html, *, maps=False, jsonld=None):
|
||||
nonlocal pages
|
||||
layout.write_page(out_dir, path, layout.layout(
|
||||
title, body_html, path=path, description=description, maps=maps, site=site, jsonld=jsonld))
|
||||
pages += 1
|
||||
|
||||
t, d, b = regions.regions_index_page(records, site)
|
||||
add("/regions/", t, d, b)
|
||||
by_slug, _ = regions.collect_regions(records)
|
||||
region_paths = []
|
||||
for slug in sorted(by_slug):
|
||||
t, d, b, needs_map = regions.region_page(slug, records, site)
|
||||
path = f"/regions/{slug}/"
|
||||
region_paths.append(path)
|
||||
add(path, t, d, b, maps=needs_map)
|
||||
t, d, b = regions.routes_page(records, site, repo_root)
|
||||
add("/routes/", t, d, b)
|
||||
t, d, b = docs.sources_page(records, site, repo_root)
|
||||
add("/sources/", t, d, b)
|
||||
t, d, b = docs.logos_page(records, site, repo_root)
|
||||
add("/logos/", t, d, b)
|
||||
t, d, b = docs.about_page(records, site, repo_root)
|
||||
add("/about/", t, d, b)
|
||||
t, d, b = docs.data_page(records, site, repo_root, out_dir)
|
||||
add("/data/", t, d, b, jsonld=dataset)
|
||||
t, d, b = docs.schema_page(site, repo_root)
|
||||
add("/data/schema/", t, d, b)
|
||||
t, d, b = docs.changelog_page(site, repo_root)
|
||||
add("/data/changelog/", t, d, b)
|
||||
docs.copy_licences(out_dir, repo_root)
|
||||
seo.write_seo_files(out_dir, seo.all_paths(records, region_paths), site)
|
||||
print(f"pages written {pages}: {len(records)} trail pages, home, 404, regions, routes, docs")
|
||||
return pages
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Load the trail records (one trail.toml per directory) with derived fields."""
|
||||
import os
|
||||
import tomllib
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SHIELD_NAMES = ("shield.svg", "shield.png")
|
||||
|
||||
|
||||
def trail_kind(rec):
|
||||
return rec.get("kind") or "designated"
|
||||
|
||||
|
||||
def trail_status(rec):
|
||||
"""Same rule as the status column of trails.csv (tools/build_index.py)."""
|
||||
return "included" if rec.get("source", {}).get("line_file") else "record-only"
|
||||
|
||||
|
||||
def find_files(root, tid, rec):
|
||||
"""Return the data files that exist for a trail, as paths relative to root."""
|
||||
d = os.path.join(root, tid)
|
||||
files = {}
|
||||
|
||||
def rel(name):
|
||||
return f"{tid}/{name}"
|
||||
|
||||
line_file = rec.get("source", {}).get("line_file") or ""
|
||||
if line_file and os.path.isfile(os.path.join(d, line_file)):
|
||||
files["line"] = rel(line_file)
|
||||
if os.path.isfile(os.path.join(d, "alternates.geojson")):
|
||||
files["alternates"] = rel("alternates.geojson")
|
||||
extracts = {}
|
||||
for name in sorted(os.listdir(d)):
|
||||
if name.startswith("line-") and name.endswith(".geojson"):
|
||||
extracts[name[len("line-"):-len(".geojson")]] = rel(name)
|
||||
if extracts:
|
||||
files["extracts"] = extracts
|
||||
for name in SHIELD_NAMES:
|
||||
if os.path.isfile(os.path.join(d, name)):
|
||||
files["shield"] = rel(name)
|
||||
break
|
||||
return files
|
||||
|
||||
|
||||
def load_record(root, tid):
|
||||
with open(os.path.join(root, tid, "trail.toml"), "rb") as f:
|
||||
rec = tomllib.load(f)
|
||||
length_km = rec.get("length_km", 0)
|
||||
rec["derived"] = {
|
||||
"kind": trail_kind(rec),
|
||||
"has_line": bool(rec.get("source", {}).get("line_file")),
|
||||
"length_mi": int(round(length_km / 1.609344)),
|
||||
"files": find_files(root, tid, rec),
|
||||
"status": trail_status(rec),
|
||||
}
|
||||
return rec
|
||||
|
||||
|
||||
def load_records(root=ROOT):
|
||||
"""Every */trail.toml under root, sorted by id."""
|
||||
ids = sorted(
|
||||
d for d in os.listdir(root)
|
||||
if os.path.isfile(os.path.join(root, d, "trail.toml"))
|
||||
)
|
||||
return [load_record(root, tid) for tid in ids]
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Region pages (/regions/, /regions/<slug>/) and the routes page (/routes/).
|
||||
|
||||
Both list records with home.results(), the same list the home page shows.
|
||||
"""
|
||||
import collections
|
||||
|
||||
from . import common, docs, home, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
# The /regions/ anchor and the finder's region key for records that name all of Canada.
|
||||
CANADA_WIDE_ID = "canada-wide"
|
||||
CANADA_WIDE_KEY = words.region_key(words.ALL_CANADA, "CA") # "CA-*"
|
||||
|
||||
|
||||
def region_country(code):
|
||||
return words.region_country(code) if code != words.ALL_CANADA else ""
|
||||
|
||||
|
||||
def region_slug(code, fallback_country=""):
|
||||
return words.region_key(code, region_country(code) or fallback_country).lower()
|
||||
|
||||
|
||||
def region_path(code, fallback_country=""):
|
||||
return f"/regions/{region_slug(code, fallback_country)}/"
|
||||
|
||||
|
||||
def collect_regions(records):
|
||||
"""slug -> {code, country, name, records}; plus Canada-wide records separately."""
|
||||
by_slug = {}
|
||||
canada_wide = []
|
||||
for r in records:
|
||||
for code in r.get("regions", []):
|
||||
if code == words.ALL_CANADA:
|
||||
canada_wide.append(r)
|
||||
continue
|
||||
country = region_country(code) or r["country"]
|
||||
slug = region_slug(code, r["country"])
|
||||
info = by_slug.setdefault(slug, {"code": code, "country": country,
|
||||
"name": words.region_name(code), "records": []})
|
||||
if all(x["id"] != r["id"] for x in info["records"]):
|
||||
info["records"].append(r)
|
||||
for info in by_slug.values():
|
||||
info["records"].sort(key=home.sort_name)
|
||||
canada_wide.sort(key=home.sort_name)
|
||||
return by_slug, canada_wide
|
||||
|
||||
|
||||
def country_records(records, country):
|
||||
"""Every record that touches a country: listed on one of its region pages, or Canada-wide."""
|
||||
return [r for r in records if country in common.countries(r)]
|
||||
|
||||
|
||||
def _bbox_attr(recs):
|
||||
boxes = [r["derived"]["bbox"] for r in recs if r["derived"].get("bbox")]
|
||||
if not boxes:
|
||||
return ""
|
||||
box = [min(b[0] for b in boxes), min(b[1] for b in boxes),
|
||||
max(b[2] for b in boxes), max(b[3] for b in boxes)]
|
||||
return f' data-bbox="{",".join(f"{v:.4f}" for v in box)}"'
|
||||
|
||||
|
||||
def _region_map(recs, title):
|
||||
ids = [r["id"] for r in recs if "line" in r["derived"]["files"]]
|
||||
if not ids:
|
||||
return ('<p class="note">No downloadable line in this region yet, so there is '
|
||||
'nothing to draw. The records below say why.</p>')
|
||||
return f"""<figure class="mapfig" data-map="overview" data-src="/data/overview.geojson" data-ids="{esc(" ".join(ids))}"{_bbox_attr(recs)}>
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
|
||||
<div class="map" role="region" aria-label="Map of lines in {esc(title)}">
|
||||
<div class="map__fallback"></div><div class="map__canvas"></div>
|
||||
<p class="map__status" role="status">The map needs JavaScript. The list below has every record.</p>
|
||||
</div>
|
||||
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
|
||||
</div>
|
||||
<figcaption class="mapfig__caption">
|
||||
<ul class="legend" aria-label="Legend"><li>{common.SWATCH_LINE}Designated trail</li>
|
||||
<li>{common.SWATCH_ROUTE}Person-defined route</li></ul>
|
||||
<p>{len(ids)} line{"s" if len(ids) != 1 else ""} in this region, simplified for display. Select a line for its name.</p>
|
||||
</figcaption>
|
||||
</figure>"""
|
||||
|
||||
|
||||
def regions_index_page(records, site):
|
||||
by_slug, canada_wide = collect_regions(records)
|
||||
blocks = ""
|
||||
tally = '<div><dt>Records</dt><dd>' + str(len(records)) + '</dd></div>'
|
||||
for country in ("US", "CA"):
|
||||
n_country = len(country_records(records, country))
|
||||
tally += (f'<div><dt><a href="#{esc(country.lower())}">{esc(words.COUNTRIES[country])}</a></dt>'
|
||||
f'<dd data-country-count="{esc(country)}">{n_country}</dd></div>')
|
||||
infos = sorted((i for i in by_slug.values() if i["country"] == country),
|
||||
key=lambda i: i["name"].lower())
|
||||
rows = ""
|
||||
for info in infos:
|
||||
lines = sum(1 for r in info["records"] if common.has_line(r))
|
||||
rows += (f'<tr><td><a href="{esc(region_path(info["code"], country))}">{esc(info["name"])}</a> '
|
||||
f'<code class="raw">{esc(info["code"])}</code></td>'
|
||||
f'<td class="num">{len(info["records"])}</td><td class="num">{lines}</td></tr>')
|
||||
extra = ""
|
||||
if country == "CA" and canada_wide:
|
||||
links = ", ".join(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>' for r in canada_wide)
|
||||
extra = (f'<div class="doc-block" id="{CANADA_WIDE_ID}"><h3>All provinces and territories</h3>'
|
||||
f'<p class="prose">These records name <em>all provinces and territories</em> rather than '
|
||||
f'one province, so they have no single region page and are not counted under each '
|
||||
f'province: {links}. <a href="/?region={esc(CANADA_WIDE_KEY)}">Open in the trail finder</a>.</p></div>')
|
||||
unit = "state" if country == "US" else "province or territory, or all of them"
|
||||
blocks += f"""<div class="doc-block"><h2 id="{esc(country.lower())}">{esc(words.COUNTRIES[country])}</h2>
|
||||
<p class="prose">{n_country} records name at least one {unit}. Each is counted once, whichever
|
||||
country it is filed under.</p>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">State, province or territory</th><th scope="col">Records</th><th scope="col">With a downloadable line</th></tr></thead>
|
||||
<tbody>{rows}</tbody></table></div>{extra}</div>"""
|
||||
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
|
||||
<div class="titleblock__text"><p class="kicker">Browse</p><h1>Regions</h1>
|
||||
<p class="page-head__lede">Every state, province and territory a record names. A record that
|
||||
crosses several regions appears on each region's page, under the country that region belongs to.</p>
|
||||
</div></header>
|
||||
<dl class="tally">{tally}</dl></div></div>
|
||||
<div class="container section">{blocks}</div>"""
|
||||
return "Regions", "Long trails by state, province and territory, with counts of records and lines.", Markup(body)
|
||||
|
||||
|
||||
def region_page(slug, records, site):
|
||||
by_slug, _ = collect_regions(records)
|
||||
info = by_slug[slug]
|
||||
recs = info["records"]
|
||||
lines = sum(1 for r in recs if common.has_line(r))
|
||||
key = words.region_key(info["code"], info["country"])
|
||||
same = sorted((s for s, i in by_slug.items() if i["country"] == info["country"]),
|
||||
key=lambda s: by_slug[s]["name"].lower())
|
||||
idx = same.index(slug)
|
||||
neighbours = []
|
||||
if idx > 0:
|
||||
p = by_slug[same[idx - 1]]
|
||||
neighbours.append(f'<a href="{esc(region_path(p["code"], p["country"]))}">← {esc(p["name"])}</a>')
|
||||
if idx + 1 < len(same):
|
||||
n = by_slug[same[idx + 1]]
|
||||
neighbours.append(f'<a href="{esc(region_path(n["code"], n["country"]))}">{esc(n["name"])} →</a>')
|
||||
nav = " · ".join(neighbours)
|
||||
with_line = (f'<a href="/?region={esc(key)}&line=1">With a line</a>' if lines else "With a line")
|
||||
body = f"""<div class="page-head"><div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/regions/">Regions</a></li>
|
||||
<li><a href="/regions/#{esc(info["country"].lower())}">{esc(words.COUNTRIES[info["country"]])}</a></li>
|
||||
<li aria-current="page">{esc(info["name"])}</li></ol></nav>
|
||||
<header class="titleblock"><div class="titleblock__text">
|
||||
<p class="kicker">{esc(words.COUNTRIES[info["country"]])} · {esc(info["code"])}</p>
|
||||
<h1>{esc(info["name"])}</h1>
|
||||
<p class="page-head__lede">{len(recs)} record{"s" if len(recs) != 1 else ""}, {lines} with a downloadable line.</p>
|
||||
</div></header>
|
||||
<dl class="tally"><div><dt>Records</dt><dd>{len(recs)}</dd></div>
|
||||
<div><dt>{common.SWATCH_LINE}{with_line}</dt><dd>{lines}</dd></div>
|
||||
<div><dt>{common.SWATCH_NONE}Records only</dt><dd>{len(recs) - lines}</dd></div></dl>
|
||||
</div></div>
|
||||
<div class="container section">
|
||||
<div class="section-head"><h2>Lines in {esc(info["name"])}</h2><p>Only lines in this region are drawn.</p></div>
|
||||
{_region_map(recs, info["name"])}
|
||||
</div>
|
||||
<div class="container section">
|
||||
<div class="section-head"><h2>Trails and routes in {esc(info["name"])}</h2>
|
||||
<p><a href="/?region={esc(key)}">Open these in the trail finder</a> to search and filter them.</p></div>
|
||||
{home.results(recs)}
|
||||
<nav class="region-nav" aria-label="Neighbouring regions"><a href="/regions/">All regions</a>{f' · {nav}' if nav else ""}</nav>
|
||||
</div>"""
|
||||
title = info["name"]
|
||||
return title, f"{len(recs)} long trails and routes in {info['name']}, {words.COUNTRIES[info['country']]}.", Markup(body), bool(lines)
|
||||
|
||||
|
||||
def route_guides(rec):
|
||||
"""A route's guides, placed last in its list row on /routes/."""
|
||||
items = ""
|
||||
for g in rec.get("guide", []):
|
||||
access = g.get("access", "")
|
||||
price = ""
|
||||
if g.get("price"):
|
||||
price = f' · {esc(g["price"])}'
|
||||
if g.get("price_checked"):
|
||||
price += f' (read {esc(g["price_checked"])})'
|
||||
fmt = f' · {esc(g["format"])}' if g.get("format") else ""
|
||||
items += (f'<li><a href="{esc(g.get("url", ""))}">{esc(g.get("title", ""))}</a>'
|
||||
f' <span class="access access--{esc(access)}">{esc(words.ACCESS.get(access, access))}</span>'
|
||||
f'{fmt}{price}</li>')
|
||||
if not items:
|
||||
return ""
|
||||
return (f'\n <div class="entry__guides"><p class="route-item__guides-label">Guides</p>'
|
||||
f'<ul class="route-guides">{items}</ul></div>')
|
||||
|
||||
|
||||
def routes_page(records, site, repo_root):
|
||||
"""(title, description, body) for /routes/."""
|
||||
readme = docs.sections_map(docs.read_doc(repo_root, "README.md"))
|
||||
inc = readme.get("Inclusion rule", "")
|
||||
paras = [p for p in inc.split("\n\n") if "Person-defined rout" in p and "at the same 50-mile floor" in p]
|
||||
bullets = [p for p in inc.split("\n\n") if "The creator sells" in p]
|
||||
explainer = "\n\n".join(paras + bullets) or readme.get("Person-defined routes", "")
|
||||
intro = docs.render_doc("## What a person-defined route is\n\n" + explainer, site)
|
||||
|
||||
policy_items = ""
|
||||
for key in ("open", "sold", "withheld", "unclear"):
|
||||
lab, short, rule = words.POLICIES[key]
|
||||
policy_items += f'<li>{common.policy_chip(key)}<span>{esc(short)}. {esc(rule)}</span></li>'
|
||||
policies = Markup(f'<ol class="policy-scale" aria-label="The four line policies">{policy_items}</ol>')
|
||||
|
||||
routes = [r for r in records if common.is_route(r)]
|
||||
by_creator = collections.defaultdict(list)
|
||||
for r in routes:
|
||||
by_creator[r.get("route", {}).get("creator", "") or "Unknown"].append(r)
|
||||
groups = [(esc(creator), sorted(by_creator[creator], key=home.sort_name), route_guides)
|
||||
for creator in sorted(by_creator, key=str.lower)]
|
||||
|
||||
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
|
||||
<div class="titleblock__text"><p class="kicker">Person-defined routes</p><h1>Routes</h1>
|
||||
<p class="page-head__lede">{len(routes)} routes worked out and published by a person or a small group.</p>
|
||||
</div></header></div></div>
|
||||
<div class="container section"><div class="prose doc">{intro}</div>
|
||||
<h2 class="doc-block">The four line policies</h2>{policies}
|
||||
<p class="prose"><a href="/?kind=route">See the routes in the trail finder</a>, or read a route below.</p></div>
|
||||
<div class="container section"><div class="section-head"><h2>Routes by creator</h2>
|
||||
<p>Each route links to its record; its guides link out to the creator's or publisher's page.</p></div>
|
||||
{home.results(groups=groups)}</div>"""
|
||||
return "Routes", f"{len(routes)} person-defined routes by creator, with line policies and guides.", Markup(body)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Sitemap, robots.txt and the JSON-LD Dataset description."""
|
||||
import html
|
||||
import os
|
||||
|
||||
from . import common
|
||||
|
||||
|
||||
# The files under /data/ listed as the dataset's distribution: (name, media type).
|
||||
DISTRIBUTION = (
|
||||
("trails.csv", "text/csv"),
|
||||
("trails.json", "application/json"),
|
||||
("index.geojson", "application/geo+json"),
|
||||
("overview.geojson", "application/geo+json"),
|
||||
("all-gpx.zip", "application/zip"),
|
||||
("all-geojson.zip", "application/zip"),
|
||||
)
|
||||
|
||||
|
||||
def dataset_jsonld(records, site):
|
||||
"""One schema.org Dataset block for the home page and /data/."""
|
||||
dist = []
|
||||
for name, fmt in DISTRIBUTION:
|
||||
url = site.canonical(f"/data/{name}") or f"/data/{name}"
|
||||
dist.append({"@type": "DataDownload", "name": name, "encodingFormat": fmt, "contentUrl": url})
|
||||
obj = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Dataset",
|
||||
"name": site.name,
|
||||
"description": site.tagline,
|
||||
"license": "https://creativecommons.org/publicdomain/zero/1.0/",
|
||||
"distribution": dist,
|
||||
"variableMeasured": ["length_km", "country", "regions", "source licence"],
|
||||
}
|
||||
if site.base_url:
|
||||
obj["url"] = site.canonical("/")
|
||||
return obj
|
||||
|
||||
|
||||
def sitemap_xml(paths, site):
|
||||
"""sitemap.xml text for site paths; caller checks site.base_url is set."""
|
||||
urls = "".join(
|
||||
f" <url><loc>{html.escape(site.canonical(p), quote=True)}</loc></url>\n"
|
||||
for p in paths)
|
||||
return ('<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
|
||||
f"{urls}</urlset>\n")
|
||||
|
||||
|
||||
def robots_txt(site):
|
||||
lines = ["User-agent: *", "Allow: /", ""]
|
||||
if site.base_url:
|
||||
lines.append(f"Sitemap: {site.canonical('/sitemap.xml')}")
|
||||
return "\n".join(lines).rstrip() + "\n"
|
||||
|
||||
|
||||
def write_seo_files(out_dir, paths, site):
|
||||
"""Write robots.txt always and sitemap.xml only with a base_url."""
|
||||
with open(os.path.join(out_dir, "robots.txt"), "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(robots_txt(site))
|
||||
sitemap = os.path.join(out_dir, "sitemap.xml")
|
||||
if site.base_url:
|
||||
with open(sitemap, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(sitemap_xml(paths, site))
|
||||
elif os.path.isfile(sitemap):
|
||||
os.remove(sitemap) # a stale sitemap with wrong URLs is worse than none
|
||||
|
||||
|
||||
def all_paths(records, region_paths):
|
||||
"""Every indexable page path, in nav order then record pages."""
|
||||
paths = ["/", "/regions/"] + list(region_paths) + [
|
||||
"/routes/", "/sources/", "/logos/", "/about/", "/data/",
|
||||
"/data/schema/", "/data/changelog/"]
|
||||
paths += [common.trail_path(r) for r in sorted(records, key=lambda r: r["id"])]
|
||||
return paths
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Site-wide settings from web/site.toml (name, tagline, base_url, repo_url, contact_url, name_lang)."""
|
||||
import functools
|
||||
import os
|
||||
import tomllib
|
||||
|
||||
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SITE_TOML = os.path.join(WEB_DIR, "site.toml")
|
||||
|
||||
|
||||
class Site:
|
||||
"""The settings every page needs. Build one with load()."""
|
||||
|
||||
def __init__(self, name, tagline, base_url="", repo_url="", contact_url="", name_lang=None):
|
||||
if not name:
|
||||
raise ValueError("site.toml: name must not be empty")
|
||||
self.name = name
|
||||
self.tagline = tagline
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.repo_url = repo_url.rstrip("/")
|
||||
self.contact_url = contact_url.strip()
|
||||
# record id -> language tag of its name ("fr"), for names that are not English
|
||||
self.name_lang = dict(name_lang or {})
|
||||
|
||||
def canonical(self, path):
|
||||
"""Absolute URL of a site path ("/trails/arizona/"), or "" when base_url is unset."""
|
||||
return self.base_url + path if self.base_url else ""
|
||||
|
||||
@property
|
||||
def issues_url(self):
|
||||
"""Where to report an error, or "" when repo_url is unset."""
|
||||
return self.repo_url + "/issues" if self.repo_url else ""
|
||||
|
||||
|
||||
def from_file(path):
|
||||
with open(path, "rb") as f:
|
||||
data = tomllib.load(f)
|
||||
return Site(name=data.get("name", ""), tagline=data.get("tagline", ""),
|
||||
base_url=data.get("base_url", ""), repo_url=data.get("repo_url", ""),
|
||||
contact_url=data.get("contact_url", ""), name_lang=data.get("name_lang", {}))
|
||||
|
||||
|
||||
@functools.cache
|
||||
def load():
|
||||
"""The settings in web/site.toml (read once per process)."""
|
||||
return from_file(SITE_TOML)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""PNG logo thumbnails for the list pages.
|
||||
|
||||
web/thumbs/<id>.png is made by web/tools/make_thumbs.py and committed. The pages
|
||||
step copies it to trails/<id>/shield-thumb.png, and the list pages show that
|
||||
copy at its real pixel size (read from the PNG header; no image library). A
|
||||
PNG logo with no thumbnail falls back to the full-size file, with a warning.
|
||||
SVG logos are not touched.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import sys
|
||||
|
||||
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
THUMB_DIR = os.path.join(WEB_DIR, "thumbs")
|
||||
THUMB_NAME = "shield-thumb.png"
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
|
||||
def png_size(path):
|
||||
"""(width, height) from the IHDR chunk at the start of a PNG file."""
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(24)
|
||||
if len(head) < 24 or head[:8] != PNG_SIGNATURE or head[12:16] != b"IHDR":
|
||||
raise ValueError(f"{path} is not a PNG file")
|
||||
return struct.unpack(">II", head[16:24])
|
||||
|
||||
|
||||
def prepare(rec, out_dir, repo_root, thumb_dir=THUMB_DIR):
|
||||
"""Copy the record's PNG thumbnail into its output directory and set
|
||||
rec["derived"]["logo_img"] = {"src", "width", "height"}, the image the list
|
||||
pages show. Without a PNG logo the key is absent and any old copy is removed.
|
||||
"""
|
||||
tid = rec["id"]
|
||||
tdir = os.path.join(out_dir, "trails", tid)
|
||||
dest = os.path.join(tdir, THUMB_NAME)
|
||||
rec["derived"].pop("logo_img", None)
|
||||
shield = rec["derived"]["files"].get("shield", "")
|
||||
if not shield.endswith(".png"):
|
||||
if os.path.isfile(dest):
|
||||
os.remove(dest)
|
||||
return
|
||||
thumb = os.path.join(thumb_dir, f"{tid}.png")
|
||||
if os.path.isfile(thumb):
|
||||
shutil.copyfile(thumb, dest)
|
||||
path, src = dest, f"/trails/{tid}/{THUMB_NAME}"
|
||||
else:
|
||||
print(f"warning: {tid}: no thumbnail at {os.path.relpath(thumb, WEB_DIR)}; "
|
||||
f"the full-size logo is shown (run web/tools/make_thumbs.py)", file=sys.stderr)
|
||||
if os.path.isfile(dest):
|
||||
os.remove(dest)
|
||||
path, src = os.path.join(repo_root, shield), f"/trails/{tid}/{os.path.basename(shield)}"
|
||||
width, height = png_size(path)
|
||||
rec["derived"]["logo_img"] = {"src": src, "width": width, "height": height}
|
||||
@@ -0,0 +1,737 @@
|
||||
"""One page per record: /trails/<id>/.
|
||||
|
||||
The main sections say what the record says, in plain words. Every field of
|
||||
the record, with its exact value, is in the table at the end of the page
|
||||
(raw_record); the main flow carries no coded values.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
from . import common, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
EXTRACT_SOURCES = {"osm": "OpenStreetMap", "usfs": "USDA Forest Service", "nps": "National Park Service"}
|
||||
GAUGE_MIN, GAUGE_MAX, GAUGE_LIMIT = -40.0, 40.0, common.LENGTH_LIMIT
|
||||
# Download formats in the order a hiker most likely wants them: GPX for devices first.
|
||||
FORMAT_ORDER = ("GPX", "GeoJSON")
|
||||
|
||||
|
||||
# Small building blocks ------------------------------------------------------
|
||||
|
||||
def code(value):
|
||||
return Markup(f'<code class="raw">{esc(value)}</code>')
|
||||
|
||||
|
||||
def fact(label, value, note=""):
|
||||
"""One label/value row of a facts list. note: smaller text under the value.
|
||||
|
||||
Plain-string values and notes are record text: escaped, with `backticked` spans set as code.
|
||||
"""
|
||||
value_html = value if isinstance(value, Markup) else common.rich(value)
|
||||
note_html = f"<small>{note if isinstance(note, Markup) else common.rich(note)}</small>" if note else ""
|
||||
return Markup(f"<div><dt>{esc(label)}</dt><dd>{value_html}{note_html}</dd></div>")
|
||||
|
||||
|
||||
def facts(*rows):
|
||||
rows = [r for r in rows if r]
|
||||
return Markup('<dl class="facts">' + "".join(rows) + "</dl>") if rows else Markup("")
|
||||
|
||||
|
||||
def ext_link(url, text=None):
|
||||
return Markup(f'<a href="{esc(url)}">{esc(text or url)}</a>')
|
||||
|
||||
|
||||
def host(url):
|
||||
netloc = urllib.parse.urlsplit(url).netloc
|
||||
return netloc[4:] if netloc.startswith("www.") else netloc
|
||||
|
||||
|
||||
def yes_no(value):
|
||||
return "Yes" if value else "No"
|
||||
|
||||
|
||||
def block(id_, title, content, extra=""):
|
||||
"""A section of the main column. Its heading carries the id; the section is not a
|
||||
landmark (no aria-labelledby): a page has many of them."""
|
||||
return Markup(f'<section class="block">'
|
||||
f'<h2 id="{id_}">{esc(title)}{extra}</h2>{content}</section>')
|
||||
|
||||
|
||||
def record_text(text, cls=""):
|
||||
return Markup(f'<p class="record-text{(" " + cls) if cls else ""}">{common.rich(text)}</p>')
|
||||
|
||||
|
||||
def restates_no_line(value):
|
||||
"""True for record values that only say there is no line ("none (no line included)")."""
|
||||
text = str(value or "").strip().lower()
|
||||
return text.startswith(("none (no line", "no line included", "no line to measure"))
|
||||
|
||||
|
||||
def region_names(rec):
|
||||
"""The regions for the title block, each linked to its region page."""
|
||||
regions = rec.get("regions", [])
|
||||
if len(regions) <= 3:
|
||||
parts = []
|
||||
for code_ in regions:
|
||||
if code_ == words.ALL_CANADA:
|
||||
href = "/regions/#canada-wide"
|
||||
else:
|
||||
href = f"/regions/{words.region_key(code_, rec['country']).lower()}/"
|
||||
parts.append(f'<a href="{esc(href)}">{esc(words.region_name(code_))}</a>')
|
||||
return Markup(", ".join(parts))
|
||||
return common.regions_html(rec, linked=True)
|
||||
|
||||
|
||||
_ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)")
|
||||
|
||||
|
||||
def org_name(text):
|
||||
"""The organisation or person a record names, without the record's own remarks:
|
||||
"Green Mountain Club (publishes the trail); its ArcGIS ..." -> "Green Mountain Club"."""
|
||||
name = _ORG_CUT.split(text or "", maxsplit=1)[0].strip()
|
||||
return name[:1].upper() + name[1:]
|
||||
|
||||
|
||||
# Page head ------------------------------------------------------------------
|
||||
|
||||
def page_head(rec):
|
||||
route = common.is_route(rec)
|
||||
country = words.COUNTRIES.get(rec["country"], rec["country"])
|
||||
crumbs = [f'<li><a href="/">Trails</a></li>',
|
||||
f'<li><a href="/?country={esc(rec["country"])}">{esc(country)}</a></li>']
|
||||
if route:
|
||||
crumbs.append('<li><a href="/?kind=route">Person-defined routes</a></li>')
|
||||
crumbs.append(f'<li aria-current="page">{common.name(rec)}</li>')
|
||||
if route:
|
||||
r = rec["route"]
|
||||
lead = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "")
|
||||
else:
|
||||
lead = rec.get("designation", "")
|
||||
sub = f'{esc(lead)} · {region_names(rec)}, {esc(country)}'
|
||||
has_plate = bool(common.shield_url(rec))
|
||||
plate = common.plate(rec, size="lg", link=True, eager=True) if has_plate else ""
|
||||
return f"""<div class="page-head">
|
||||
<div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{"".join(crumbs)}</ol></nav>
|
||||
<header class="titleblock{" titleblock--with-plate" if has_plate else ""}">
|
||||
{plate}
|
||||
<div class="titleblock__text">
|
||||
<p class="cluster">{common.tags(rec)}</p>
|
||||
<h1>{common.name(rec)} <span class="titleblock__abbr">{esc(rec.get("short_name", ""))}</span></h1>
|
||||
<p class="titleblock__sub">{sub}</p>
|
||||
</div>
|
||||
</header>
|
||||
{tally(rec)}
|
||||
</div>
|
||||
</div>"""
|
||||
|
||||
|
||||
def tally(rec):
|
||||
v = rec.get("verification", {})
|
||||
note = rec.get("length_note", "")
|
||||
if note.replace(",", "") in (f"{rec['length_km']} km", f"{rec['length_km']} km published"):
|
||||
note = "" # the note only repeats the number
|
||||
items = [("Published length", words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]), note)]
|
||||
if v.get("verified") and "measured_km" in v:
|
||||
diff = v.get("difference_percent", 0)
|
||||
items.append(("Measured line", words.length(v["measured_km"], "stack", measured=True),
|
||||
f"{words.fmt_percent(diff)} against published"))
|
||||
else:
|
||||
items.append(("Measured line", Markup('<span class="tally__none">Not measured</span>'),
|
||||
"No line was downloaded and measured"))
|
||||
if common.has_line(rec):
|
||||
text = "In the dataset, partial" if common.line_short(rec) else "In the dataset"
|
||||
link = Markup(f'<a href="#download">{esc(text)}</a>') if rec["derived"].get("downloads") else text
|
||||
items.append(("Line", link, "Licence: " + common.licence_label(rec)))
|
||||
else:
|
||||
items.append(("Line", "Record only", "The reason is given below"))
|
||||
if common.is_route(rec):
|
||||
p = common.policy(rec)
|
||||
items.append(("Line policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p)))
|
||||
else:
|
||||
t = rec.get("tier", "")
|
||||
items.append(("Tier", words.label(words.TIERS, t), words.meaning(words.TIERS, t)))
|
||||
cells = "".join(f'<div><dt>{esc(a)}</dt><dd>{esc(b)}{f"<small>{esc(c)}</small>" if c else ""}</dd></div>'
|
||||
for a, b, c in items)
|
||||
return Markup(f'<dl class="tally tally--trail">{cells}</dl>')
|
||||
|
||||
|
||||
# Map or empty frame ---------------------------------------------------------
|
||||
|
||||
def map_figure(rec):
|
||||
src = rec["source"]
|
||||
has_alt = "alternates" in rec["derived"]["files"]
|
||||
route = common.is_route(rec)
|
||||
legend = f'<li>{common.SWATCH_ROUTE if route else common.SWATCH_LINE}Main line</li>'
|
||||
if has_alt:
|
||||
legend += f"<li>{common.SWATCH_ALT}Alternates and connectors</li>"
|
||||
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}>
|
||||
<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"])}">
|
||||
<div class="map__fallback"></div>
|
||||
<div class="map__canvas"></div>
|
||||
<p class="map__status" role="status">The map needs JavaScript. Download the line from this page.</p>
|
||||
</div>
|
||||
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
|
||||
</div>
|
||||
<figcaption class="mapfig__caption">
|
||||
<ul class="legend" aria-label="Legend">{legend}</ul>
|
||||
<p>Line: {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.</p>
|
||||
</figcaption>
|
||||
</figure>"""
|
||||
|
||||
|
||||
def free_guides(rec):
|
||||
return [g for g in rec.get("guide", []) if g.get("access") == "free"]
|
||||
|
||||
|
||||
def empty_frame(rec):
|
||||
src = rec["source"]
|
||||
reason = src.get("line_absent_reason", "")
|
||||
actions = []
|
||||
if common.is_route(rec):
|
||||
p = common.policy(rec)
|
||||
titles = {
|
||||
"open": "Get the line from the creator",
|
||||
"sold": "The line is sold as a guide",
|
||||
"withheld": "The creator does not publish a line",
|
||||
"unclear": "Whether the line may be shared is not settled",
|
||||
}
|
||||
title = titles.get(p, "No line in this dataset")
|
||||
rule = words.POLICIES.get(p, ("", "", ""))[2]
|
||||
if p == "open" and free_guides(rec):
|
||||
g = free_guides(rec)[0]
|
||||
actions.append(f'<a class="button button--primary" href="{esc(g["url"])}">'
|
||||
f'{esc(g["title"])} {common.ICON_EXTERNAL}</a>')
|
||||
if not actions:
|
||||
actions.append('<a class="button button--link" href="#guides-title">See where to get the route</a>')
|
||||
elif len(rec.get("guide", [])) > 1:
|
||||
actions.append('<a class="button button--link" href="#guides-title">All guides</a>')
|
||||
else:
|
||||
title = "No line in this dataset"
|
||||
reason = common.absent_reason_short(rec)
|
||||
rule = "A trail may be listed as a record only, with no line, when no line for it may be shared. The record says why."
|
||||
if src.get("publisher_url"):
|
||||
actions.append(f'<a class="button button--link" href="{esc(src["publisher_url"])}">'
|
||||
f'Publisher’s page {common.ICON_EXTERNAL}</a>')
|
||||
elif src.get("url"):
|
||||
actions.append(f'<a class="button button--link" href="{esc(src["url"])}">'
|
||||
f'The source {common.ICON_EXTERNAL}</a>')
|
||||
actions_html = f'<p class="cluster">{"".join(actions)}</p>' if actions else ""
|
||||
return f"""<figure class="mapfig mapfig--empty detail__map" aria-labelledby="noline-title">
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true">No line in this dataset</span>
|
||||
<div class="map map--empty">
|
||||
<div class="map__message">
|
||||
<p class="kicker">Record only</p>
|
||||
<h2 id="noline-title">{esc(title)}</h2>
|
||||
<p>{common.rich(reason)}</p>
|
||||
<p class="note">{esc(rule)}</p>
|
||||
{actions_html}
|
||||
</div>
|
||||
</div>
|
||||
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true">Nothing drawn</span>
|
||||
</div>
|
||||
<figcaption class="mapfig__caption"><p>No map is drawn: the dataset holds no line for this {"route" if common.is_route(rec) else "trail"}, and does not guess one.</p></figcaption>
|
||||
</figure>"""
|
||||
|
||||
|
||||
# Aside: downloads, guides, links --------------------------------------------
|
||||
|
||||
def ordered_downloads(items):
|
||||
"""GPX first, then GeoJSON, then anything else, each keeping its order."""
|
||||
rank = {f: i for i, f in enumerate(FORMAT_ORDER)}
|
||||
return sorted(items, key=lambda d: rank.get(d["format"], len(rank)))
|
||||
|
||||
|
||||
def download_group(rec, label, swatch, note, items, gid):
|
||||
"""One group of download buttons. GPX comes first and is the primary button. Each
|
||||
link's accessible name starts with the group: "Main line: GPX, 1.1 MB"."""
|
||||
buttons = "".join(
|
||||
f'<a class="button{" button--primary" if d["format"] == "GPX" else ""}" '
|
||||
f'href="/trails/{esc(rec["id"])}/{esc(d["file"])}" download="{esc(d["file"])}">'
|
||||
f'{common.ICON_DOWNLOAD}<span class="vh">{esc(label)}: </span>{esc(d["format"])}<span class="vh">,</span> '
|
||||
f'<span class="button__meta">{esc(words.fmt_bytes(d["bytes"]))}</span></a>'
|
||||
for d in ordered_downloads(items))
|
||||
return f"""<li class="download">
|
||||
<p class="download__what">{swatch}<strong id="{gid}">{esc(label)}</strong><small>{esc(note)}</small></p>
|
||||
<div class="download__files">{buttons}</div>
|
||||
</li>"""
|
||||
|
||||
|
||||
def partial_notice(rec):
|
||||
"""The notice above the buttons when the line differs from the published length
|
||||
by more than 15%: the record's own numbers, then its length_gap_note."""
|
||||
if not common.line_differs(rec):
|
||||
return ""
|
||||
v = rec["verification"]
|
||||
diff = v["difference_percent"]
|
||||
head = "Partial line" if diff < 0 else "Longer than the published length"
|
||||
gap = rec["source"].get("length_gap_note", "")
|
||||
return f"""<div class="notice notice--partial">
|
||||
<h3>{head}</h3>
|
||||
<p>The line in the dataset measures {esc(words.fmt_km1(v["measured_km"]))} km against a published {esc(words.fmt_km(rec["length_km"]))} km ({esc(words.fmt_percent(diff))}).</p>
|
||||
{f"<p>{common.rich(gap)}</p>" if gap else ""}
|
||||
</div>"""
|
||||
|
||||
|
||||
def downloads_panel(rec):
|
||||
downloads = rec["derived"].get("downloads", [])
|
||||
if not downloads:
|
||||
return ""
|
||||
src = rec["source"]
|
||||
v = rec.get("verification", {})
|
||||
groups = []
|
||||
main = [d for d in downloads if d["role"] == "main"]
|
||||
if main:
|
||||
note = f"{src.get('line_source', '')}"
|
||||
if v.get("verified") and "measured_km" in v:
|
||||
parts = v.get("parts")
|
||||
note = (f"{words.fmt_km1(v['measured_km'])} km measured"
|
||||
+ (f" in {parts} part{'s' if parts != 1 else ''}" if parts else "") + f" · {note}")
|
||||
groups.append(download_group(rec, "Main line", common.SWATCH_ROUTE if common.is_route(rec) else common.SWATCH_LINE,
|
||||
note, main, "dl-main"))
|
||||
alts = [d for d in downloads if d["role"] == "alternates"]
|
||||
if alts:
|
||||
groups.append(download_group(rec, "Alternates and connectors", common.SWATCH_ALT,
|
||||
"Served separately by the source", alts, "dl-alt"))
|
||||
for i, d in enumerate(d for d in downloads if d["role"] == "extract"):
|
||||
key = d["file"][len(rec["id"]) + 1:-len(".geojson")]
|
||||
name = EXTRACT_SOURCES.get(key, key)
|
||||
# No swatch: extracts are not drawn on the map.
|
||||
groups.append(download_group(rec, f"Extract: {name}", "",
|
||||
"The line as this source serves it, before the sources were combined",
|
||||
[d], f"dl-x{i}"))
|
||||
licence = src.get("licence", "")
|
||||
licence_html = esc(words.label(words.LICENCES, licence))
|
||||
if licence in words.LICENCE_URLS:
|
||||
licence_html = ext_link(words.LICENCE_URLS[licence], words.label(words.LICENCES, licence))
|
||||
if "ODbL" in src.get("attribution", "") and licence != "ODbL-1.0":
|
||||
licence_html = Markup(f'{licence_html}; OpenStreetMap parts {ext_link(words.LICENCE_URLS["ODbL-1.0"], "ODbL 1.0")}')
|
||||
osm_note = ("<p class=\"note\">Lines from OpenStreetMap need the credit “© OpenStreetMap contributors” "
|
||||
"and stay under the ODbL (share-alike).</p>") if "ODbL" in src.get("attribution", "") + licence else ""
|
||||
release = (f'<p class="note"><a href="/trails/{esc(rec["id"])}/release.txt">release.txt</a>: '
|
||||
f"the source, licence and date the line files came from.</p>"
|
||||
if rec["derived"].get("release") else "")
|
||||
return f"""<section class="panel" id="download" aria-labelledby="download-title">
|
||||
<h2 class="panel__head" id="download-title">Download the line</h2>
|
||||
<div class="panel__body">
|
||||
{partial_notice(rec)}
|
||||
<p class="note">GPX is simplified to 5 m for devices. GeoJSON is the full-resolution line as published in this dataset. Neither carries elevation.</p>
|
||||
<ul class="downloads">{"".join(groups)}</ul>
|
||||
<div class="credit">
|
||||
<p class="credit__label" id="credit-label">Credit the source</p>
|
||||
<p class="credit__text" id="credit-text">{esc(common.credit_text(src.get("attribution", "")))}</p>
|
||||
<div class="credit__row">
|
||||
<span class="credit__licence">Licence: {licence_html}</span>
|
||||
<button class="button button--quiet" type="button" data-copy="#credit-text" data-copy-status="#credit-done" aria-describedby="credit-label" hidden>Copy credit</button>
|
||||
</div>
|
||||
<p class="credit__done" id="credit-done" role="status"></p>
|
||||
{osm_note}
|
||||
</div>
|
||||
{release}
|
||||
</div>
|
||||
</section>"""
|
||||
|
||||
|
||||
def guide_card(g, i):
|
||||
rows = [fact("Author", g.get("author", ""))]
|
||||
if g.get("publisher"):
|
||||
rows.append(fact("Publisher", g["publisher"]))
|
||||
if g.get("isbn"):
|
||||
rows.append(Markup(f'<div><dt>ISBN</dt><dd><span class="nowrap">{esc(g["isbn"])}</span></dd></div>'))
|
||||
rows.append(fact("Format", g.get("format", "")))
|
||||
if g.get("price"):
|
||||
rows.append(fact("Price", g["price"], f"As the page stated it on {g.get('price_checked', '')}"
|
||||
if g.get("price_checked") else ""))
|
||||
access = g.get("access", "")
|
||||
return f"""<li class="guide">
|
||||
<p class="guide__tags"><span class="access access--{esc(access)}">{esc(words.ACCESS.get(access, access))}</span></p>
|
||||
<h3 id="guide-{i}">{esc(g.get("title", ""))}</h3>
|
||||
{facts(*rows)}
|
||||
<a class="button button--link" href="{esc(g.get("url", ""))}" aria-describedby="guide-{i}">Guide page on {esc(host(g.get("url", "")))} {common.ICON_EXTERNAL}</a>
|
||||
</li>"""
|
||||
|
||||
|
||||
def guides_panel(rec):
|
||||
guides = rec.get("guide", [])
|
||||
if not guides:
|
||||
return ""
|
||||
cards = "".join(guide_card(g, i) for i, g in enumerate(guides, 1))
|
||||
return f"""<section class="panel" aria-labelledby="guides-title">
|
||||
<h2 class="panel__head" id="guides-title">Where to get the route</h2>
|
||||
<div class="panel__body">
|
||||
<ul class="guides">{cards}</ul>
|
||||
<p class="note">Links go to the creator’s or publisher’s own page for each guide.</p>
|
||||
</div>
|
||||
</section>"""
|
||||
|
||||
|
||||
def _is_url(value):
|
||||
return isinstance(value, str) and value.startswith(("http://", "https://"))
|
||||
|
||||
|
||||
def links_panel(rec):
|
||||
"""Every link the record holds, each titled with the organisation or person the
|
||||
record names for it, with the host name and what the link is as secondary text."""
|
||||
src = rec["source"]
|
||||
osm = rec.get("osm", {})
|
||||
sh = rec.get("shield", {})
|
||||
publisher = org_name(src.get("publisher", ""))
|
||||
items = {} # url -> [title, [what it is, ...]]; one entry per URL, titled by its first use
|
||||
|
||||
def add(url, title, what):
|
||||
if url in items:
|
||||
items[url][1].append(what)
|
||||
else:
|
||||
items[url] = [title, [what]]
|
||||
|
||||
kind = "route" if common.is_route(rec) else "trail"
|
||||
if src.get("publisher_url"):
|
||||
add(src["publisher_url"], publisher or host(src["publisher_url"]), f"The publisher's page for the {kind}")
|
||||
if osm.get("relation"):
|
||||
add(f"https://www.openstreetmap.org/relation/{osm['relation']}",
|
||||
f"OpenStreetMap relation {osm['relation']}", f"The {kind} as mapped in OpenStreetMap")
|
||||
if src.get("url"):
|
||||
what = "Where the included line came from" if common.has_line(rec) else "Where to ask for the line"
|
||||
title = "OpenStreetMap" if host(src["url"]).endswith("openstreetmap.org") else (publisher or host(src["url"]))
|
||||
add(src["url"], title, what)
|
||||
for g in rec.get("guide", []):
|
||||
if g.get("url") in items:
|
||||
add(g["url"], "", "A guide to the route")
|
||||
words_url = rec.get("route", {}).get("creator_words_url")
|
||||
if words_url:
|
||||
by = rec["route"].get("creator_words_by") or rec["route"].get("creator", "")
|
||||
add(words_url, by or host(words_url), "Where the quoted words were read")
|
||||
if _is_url(sh.get("logo_source")):
|
||||
owner = sh.get("logo_owner") or sh.get("contact") or host(sh["logo_source"])
|
||||
add(sh["logo_source"], owner, "The page the logo was taken from")
|
||||
add(f"/trails/{rec['id']}/trail.toml", "trail.toml", "The record itself, as data")
|
||||
if rec["derived"].get("release"):
|
||||
add(f"/trails/{rec['id']}/release.txt", "release.txt", "Source, licence and date of the line files")
|
||||
|
||||
def describe(url, whats):
|
||||
text = "; ".join([whats[0]] + [w[:1].lower() + w[1:] for w in whats[1:]])
|
||||
return f"{host(url)} · {text}" if _is_url(url) else text
|
||||
|
||||
lis = "".join(f'<li>{ext_link(u, t)}<small>{esc(describe(u, w))}</small></li>' for u, (t, w) in items.items())
|
||||
return f"""<section class="panel" aria-labelledby="links-title">
|
||||
<h2 class="panel__head" id="links-title">Links</h2>
|
||||
<div class="panel__body"><ul class="linklist">{lis}</ul></div>
|
||||
</section>"""
|
||||
|
||||
|
||||
# Main column ----------------------------------------------------------------
|
||||
|
||||
def policy_scale(current):
|
||||
items = []
|
||||
for p in ("open", "sold", "withheld", "unclear"):
|
||||
lab, short, rule = words.POLICIES[p]
|
||||
here = ' aria-current="true"' if p == current else ""
|
||||
mark = '<span class="policy-scale__here">This route</span>' if p == current else ""
|
||||
items.append(f'<li{here}>{common.policy_chip(p)}<span>{esc(short)}. {esc(rule)}</span>{mark}</li>')
|
||||
return Markup(f'<ol class="policy-scale" aria-label="Line policies for person-defined routes">{"".join(items)}</ol>')
|
||||
|
||||
|
||||
def route_block(rec):
|
||||
r = rec["route"]
|
||||
p = r.get("line_policy", "")
|
||||
rows = [
|
||||
fact("Creator", r.get("creator", "")),
|
||||
fact("First published", str(r["year"])) if r.get("year") else
|
||||
fact("First published", "Not recorded", "No page read states a year"),
|
||||
fact("Line policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p)),
|
||||
]
|
||||
quote = ""
|
||||
if r.get("creator_words"):
|
||||
by = r.get("creator_words_by") or r.get("creator", "")
|
||||
not_creator = ('<span class="tag tag--quiet">Not the creator’s words</span>'
|
||||
if r.get("creator_words_by") else '<span class="tag tag--quiet">The creator’s words</span>')
|
||||
url = r.get("creator_words_url", "")
|
||||
quote = f"""<figure class="quote">
|
||||
<blockquote{f' cite="{esc(url)}"' if url else ""}><p>{esc(r["creator_words"])}</p></blockquote>
|
||||
<figcaption>
|
||||
<p class="quote__who"><strong>{esc(by)}</strong> {not_creator}</p>
|
||||
{f'<p>Read on {ext_link(url)}.</p>' if url else ""}
|
||||
</figcaption>
|
||||
</figure>"""
|
||||
note = f'<h3 class="block__sub">About the route</h3>{record_text(r["note"])}' if r.get("note") else ""
|
||||
return block("route-title", "The route", facts(*rows) + Markup(quote) + policy_scale(p) + Markup(note))
|
||||
|
||||
|
||||
def listing_note(rec):
|
||||
"""The Listing row's note. A held record is listed but not settled; its wave_note
|
||||
(quoted, never paraphrased) says what. Other records show their wave_note as it is."""
|
||||
wave = str(rec.get("wave", ""))
|
||||
note = rec.get("wave_note", "")
|
||||
if wave != "held":
|
||||
return note or words.meaning(words.WAVES, wave)
|
||||
meaning = words.meaning(words.WAVES, wave)
|
||||
if note:
|
||||
return Markup(f"{esc(meaning)}. The record’s note: “{common.rich(note)}”")
|
||||
return f"{meaning}. The record has no note saying what."
|
||||
|
||||
|
||||
def record_block(rec):
|
||||
k = common.kind(rec)
|
||||
tier = rec.get("tier", "")
|
||||
wave = str(rec.get("wave", ""))
|
||||
country = words.COUNTRIES.get(rec["country"], rec["country"])
|
||||
names = ", ".join(words.region_name(c) for c in rec.get("regions", []) if c != words.ALL_CANADA)
|
||||
names_html = f' <span class="muted">({esc(names)})</span>' if names else ""
|
||||
where = Markup(f'{common.regions_html(rec, linked=True)}{names_html}, {esc(country)}')
|
||||
rows = [
|
||||
fact("Kind", words.label(words.KINDS, k), words.meaning(words.KINDS, k)),
|
||||
fact("Designation", rec.get("designation", "")),
|
||||
fact("Tier", words.label(words.TIERS, tier), words.meaning(words.TIERS, tier)),
|
||||
fact("Listing", words.label(words.WAVES, wave), listing_note(rec)),
|
||||
]
|
||||
if rec.get("inclusion"):
|
||||
inc = rec["inclusion"]
|
||||
rows.append(fact("Inclusion", words.label(words.INCLUSION, inc), words.meaning(words.INCLUSION, inc)))
|
||||
rows += [
|
||||
Markup(f'<div><dt>Where</dt><dd>{where}</dd></div>'),
|
||||
Markup(f'<div><dt>Published length</dt><dd>{words.length(rec["length_km"], "inline", rec["derived"]["length_mi"])}'
|
||||
f'<small>{esc(rec.get("length_note", ""))}. A check value, not measured from the line.</small></dd></div>'),
|
||||
fact("Short name", rec.get("short_name", "")),
|
||||
fact("Record ID", Markup(code(rec["id"])), "Stable: the directory name, never changed"),
|
||||
]
|
||||
return block("record-title", "The record", facts(*rows))
|
||||
|
||||
|
||||
def gauge(diff):
|
||||
span = GAUGE_MAX - GAUGE_MIN
|
||||
pos = (min(max(diff, GAUGE_MIN), GAUGE_MAX) - GAUGE_MIN) / span * 100
|
||||
off = "low" if diff < GAUGE_MIN else "high" if diff > GAUGE_MAX else ""
|
||||
inside = abs(diff) <= GAUGE_LIMIT
|
||||
side = "shorter than" if diff < 0 else "longer than" if diff > 0 else "the same as"
|
||||
label = (f"Measured line is {abs(diff):.1f} percent {side} the published length, "
|
||||
f"{'inside' if inside else 'outside'} the 15 percent limit.")
|
||||
mark_text = words.fmt_percent(diff) + (" (off the scale)" if off else "")
|
||||
ticks = (GAUGE_MIN, -GAUGE_LIMIT, 0, GAUGE_LIMIT, GAUGE_MAX) # placed by .gauge__tick--N in style.css
|
||||
scale = "".join(f'<span class="gauge__tick--{i}">{esc(words.fmt_percent(v).replace(".0%", "%") if v else "0")}</span>'
|
||||
for i, v in enumerate(ticks))
|
||||
return Markup(f"""<figure class="gauge{f" gauge--off-{off}" if off else ""}">
|
||||
<div class="gauge__track" role="img" aria-label="{esc(label)}">
|
||||
<span class="gauge__band"></span>
|
||||
<span class="gauge__zero"></span>
|
||||
<span class="gauge__mark" style="--pos: {pos:.2f}%" data-label="{esc(mark_text)}"></span>
|
||||
</div>
|
||||
<div class="gauge__scale" aria-hidden="true">{scale}</div>
|
||||
<figcaption class="gauge__legend">
|
||||
<span><span class="gauge__key" aria-hidden="true"></span>Within 15% of the published length</span>
|
||||
<span><span class="gauge__key gauge__key--out" aria-hidden="true"></span>Beyond 15%: the record must say why</span>
|
||||
</figcaption>
|
||||
</figure>""")
|
||||
|
||||
|
||||
def verification_block(rec):
|
||||
v = rec.get("verification", {})
|
||||
src = rec["source"]
|
||||
gap = src.get("length_gap_note", "")
|
||||
if gap and common.line_differs(rec) and rec["derived"].get("downloads"):
|
||||
# The download panel's notice carries the note, beside the files it is about.
|
||||
gap_html = '<p class="note">Why the lengths differ: see the notice in <a href="#download">Download the line</a>.</p>'
|
||||
elif gap:
|
||||
gap_html = f'<div class="notice"><h3>Why the lengths differ</h3><p>{common.rich(gap)}</p></div>'
|
||||
else:
|
||||
gap_html = ""
|
||||
if v.get("verified") and "measured_km" in v:
|
||||
diff = v.get("difference_percent", 0)
|
||||
parts = v.get("parts")
|
||||
compare = f"""<dl class="compare">
|
||||
<div><dt>Published</dt><dd>{words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}</dd></div>
|
||||
<div><dt>Measured</dt><dd>{words.length(v["measured_km"], "stack", measured=True)}<small>geodesic, from the line</small></dd></div>
|
||||
<div><dt>Difference</dt><dd>{esc(words.fmt_percent(diff))}<small>measured minus published</small></dd></div>
|
||||
<div><dt>Parts</dt><dd>{esc(parts if parts is not None else "Not recorded")}<small>pieces left after joining ends within 100 m</small></dd></div>
|
||||
</dl>"""
|
||||
content = Markup(compare) + gauge(diff) + record_text(v.get("note", "")) + Markup(gap_html)
|
||||
extra = Markup(f' <span class="tag">Checked {esc(v.get("date", ""))}</span>') if v.get("date") else ""
|
||||
verified_row = facts(fact("Measured", "Yes", "The line was downloaded and measured"))
|
||||
return block("verify-title", "Verification", verified_row + content, extra)
|
||||
if not common.has_line(rec) and restates_no_line(v.get("note", "")) and not gap:
|
||||
return "" # "No line to measure": the record only restates that there is no line
|
||||
rows = facts(fact("Measured", "No", "No line was downloaded and measured"))
|
||||
return block("verify-title", "Verification", rows + record_text(v.get("note", "")) + Markup(gap_html))
|
||||
|
||||
|
||||
def source_block(rec):
|
||||
src = rec["source"]
|
||||
line = common.has_line(rec)
|
||||
status = src.get("status", "")
|
||||
licence = src.get("licence", "")
|
||||
licence_value = words.label(words.LICENCES, licence)
|
||||
licence_html = (ext_link(words.LICENCE_URLS[licence], licence_value) if licence in words.LICENCE_URLS
|
||||
else esc(licence_value))
|
||||
source_help = '<small>Where to ask for the line: a layer or relation page</small>' if line else ""
|
||||
|
||||
def keep(value):
|
||||
"""Rows of a record with no line are left out when they only restate that."""
|
||||
return line or not restates_no_line(value)
|
||||
|
||||
rows = [
|
||||
fact("Line in this dataset", src.get("line_file"), "The main line file of the record") if line else "",
|
||||
fact("Source status", words.label(words.SOURCE_STATUS, status), words.meaning(words.SOURCE_STATUS, status)),
|
||||
fact("Publisher", src.get("publisher", "")),
|
||||
Markup(f'<div><dt>Publisher’s page</dt><dd>{ext_link(src["publisher_url"])}</dd></div>') if src.get("publisher_url") else "",
|
||||
Markup(f'<div><dt>Source</dt><dd>{ext_link(src["url"])}{source_help}</dd></div>') if src.get("url") else "",
|
||||
fact("Line source", src.get("line_source", "")) if keep(src.get("line_source")) else "",
|
||||
fact("Format", src.get("format", "")) if keep(src.get("format")) else "",
|
||||
fact("Main line", src.get("mainline", ""), "How the main line is told apart from alternates, connectors and side trails"),
|
||||
fact("Coordinates", src.get("crs", ""), "What the source stores; published files are longitude/latitude (EPSG:4326)") if line else "",
|
||||
Markup(f'<div><dt>Licence</dt><dd>{licence_html}</dd></div>'),
|
||||
fact("Credit", common.credit_text(src.get("attribution", "")), "The credit line to show, as the source asks")
|
||||
if keep(src.get("attribution")) else "",
|
||||
fact("May be passed on", yes_no(src.get("redistributable")),
|
||||
"The source's terms allow its line to be passed on" if src.get("redistributable") else
|
||||
"The source's terms do not allow its line to be passed on") if line else "",
|
||||
fact("OpenStreetMap only", yes_no(src.get("osm_only")),
|
||||
"OpenStreetMap is the only source of the included line" if src.get("osm_only") else "") if line else "",
|
||||
fact("Source checked", src.get("source_checked", "")),
|
||||
fact("Newer release?", src["discovery"], "How to tell whether the source has a newer release") if src.get("discovery") else "",
|
||||
]
|
||||
if src.get("decision") or src.get("decision_text"):
|
||||
rows.append(fact("Decision", src.get("decision_text", "") or words.DECISIONS.get(src.get("decision", ""), src.get("decision", ""))))
|
||||
licence_text = (f'<h3 class="block__sub">What the source says</h3>{record_text(src["licence_text"])}'
|
||||
'<p class="note">With the page it was read on. Not legal advice.</p>') if src.get("licence_text") else ""
|
||||
return block("source-title", "Source and licence", facts(*rows) + Markup(licence_text))
|
||||
|
||||
|
||||
def osm_block(rec):
|
||||
osm = rec.get("osm", {})
|
||||
rel = osm.get("relation", 0)
|
||||
if rel:
|
||||
value = Markup(f'<div><dt>Relation</dt><dd>{ext_link(f"https://www.openstreetmap.org/relation/{rel}", str(rel))}</dd></div>')
|
||||
elif common.has_line(rec):
|
||||
value = fact("Relation", "None recorded", "No relation found, or not searched")
|
||||
else:
|
||||
value = "" # no line and no relation: nothing to say beyond the note
|
||||
return block("osm-title", "OpenStreetMap", facts(value, fact("Note", osm.get("note", ""))))
|
||||
|
||||
|
||||
def logo_block(rec):
|
||||
sh = rec.get("shield", {})
|
||||
status = sh.get("status", "")
|
||||
if not common.shield_url(rec):
|
||||
# No logo file: one line, the status and the record's note.
|
||||
lead = {"no-logo-exists": "No logo", "logo-not-found": "Logo not found",
|
||||
"use-real-logo": "Logo not included"}.get(status, "No logo file")
|
||||
note = sh.get("note", "")
|
||||
return block("logo-title", "Logo", Markup(
|
||||
f'<p class="record-text"><strong>{esc(lead)}.</strong>{" " + common.rich(note) if note else ""}</p>'))
|
||||
rows = [
|
||||
fact("Status", words.label(words.SHIELD_STATUS, status), words.meaning(words.SHIELD_STATUS, status)),
|
||||
fact("Holder", sh.get("logo_owner", "")) if sh.get("logo_owner") else "",
|
||||
fact("Contact", sh.get("contact", "")) if sh.get("contact") and sh.get("contact") != sh.get("logo_owner") else "",
|
||||
Markup(f'<div><dt>Taken from</dt><dd>{ext_link(sh["logo_source"])}</dd></div>') if _is_url(sh.get("logo_source"))
|
||||
else fact("Taken from", sh.get("logo_source") or "Not recorded"),
|
||||
fact("File", sh.get("logo_file", "")),
|
||||
fact("Note", sh.get("note", "")),
|
||||
]
|
||||
federal = ("<p>Some logos are official emblems of United States National Scenic or Historic Trails. "
|
||||
"Those emblems are federal insignia; their use here is for identification only.</p>"
|
||||
if rec.get("tier") == "national" or "National Historic Trail" in rec.get("designation", "") else "")
|
||||
notice = f"""<div class="notice">
|
||||
<h3>Shown only to identify the trail</h3>
|
||||
<p>This logo belongs to {esc(sh.get("logo_owner", "its holder"))}. It is not covered by this dataset’s licences, and no right to use it for any other purpose is given or implied.</p>
|
||||
{federal}
|
||||
<p>A holder who wants a logo removed, replaced or credited differently can ask; see <a href="/logos/">Logos</a>.</p>
|
||||
</div>"""
|
||||
return block("logo-title", "Logo", Markup(notice) + facts(*rows))
|
||||
|
||||
|
||||
def correction_block(rec, site):
|
||||
parts = []
|
||||
if common.is_route(rec):
|
||||
parts.append(f"""<div class="notice">
|
||||
<h3>If you made this route</h3>
|
||||
<p>A route’s creator can ask for its record to be corrected or removed, and the record will be corrected or removed. Say which route: {code(rec["id"])}. See <a href="/about/">About</a>.</p>
|
||||
</div>""")
|
||||
if site.issues_url:
|
||||
parts.append(f"""<p class="prose">Found an error? <a href="{esc(site.issues_url)}">Open an issue</a> with the record ID ({code(rec["id"])}), what is wrong, and where the correct information can be checked: a source page, a map, or a measured line.</p>""")
|
||||
if not parts:
|
||||
return ""
|
||||
return block("correct-title", "Corrections", Markup("".join(parts)))
|
||||
|
||||
|
||||
def flatten(obj, prefix=""):
|
||||
"""(field, value) for every leaf of a record: "source.licence", "guide[0].title", "regions[1]"."""
|
||||
if isinstance(obj, dict):
|
||||
for k, v in obj.items():
|
||||
yield from flatten(v, f"{prefix}.{k}" if prefix else k)
|
||||
elif isinstance(obj, list):
|
||||
for i, v in enumerate(obj):
|
||||
yield from flatten(v, f"{prefix}[{i}]")
|
||||
else:
|
||||
yield prefix, obj
|
||||
|
||||
|
||||
def raw_value(value):
|
||||
"""A value as the record stores it: true/false, numbers as written, "" for an empty string."""
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
if isinstance(value, str):
|
||||
return value if value else '""'
|
||||
return str(value)
|
||||
|
||||
|
||||
def raw_record(rec):
|
||||
"""Every field of the record with its exact value, as the last block of the page."""
|
||||
fields = {k: v for k, v in rec.items() if k != "derived"}
|
||||
rows = "".join(f'<tr><th scope="row"><code>{esc(field)}</code></th><td>{esc(raw_value(value))}</td></tr>'
|
||||
for field, value in flatten(fields))
|
||||
return Markup(f"""<details class="rawrecord">
|
||||
<summary>Every field of the record, with its exact value</summary>
|
||||
<p class="note">As stored in <a href="/trails/{esc(rec["id"])}/trail.toml">trail.toml</a>.
|
||||
The <a href="/data/schema/">record schema</a> says what each field means.</p>
|
||||
<div class="table-wrap"><table class="rawrecord__table">
|
||||
<thead><tr><th scope="col">Field</th><th scope="col">Value</th></tr></thead>
|
||||
<tbody>{rows}</tbody>
|
||||
</table></div>
|
||||
</details>""")
|
||||
|
||||
|
||||
# The page -------------------------------------------------------------------
|
||||
|
||||
def description(rec):
|
||||
km = words.fmt_km(rec["length_km"])
|
||||
mi = words.fmt_int(rec["derived"]["length_mi"])
|
||||
where = ", ".join(words.region_name(c) for c in rec.get("regions", [])[:3])
|
||||
if len(rec.get("regions", [])) > 3:
|
||||
where += " and more"
|
||||
kind = "person-defined route" if common.is_route(rec) else "long trail"
|
||||
text = f"{rec['name']}: a {km} km ({mi} mi) {kind} in {where}. "
|
||||
if common.has_line(rec):
|
||||
text += "Download its line as GeoJSON or GPX, with the source, licence and credit."
|
||||
else:
|
||||
text += "Record only: " + common.absent_reason_short(rec)
|
||||
return text if len(text) <= 300 else text[:297].rsplit(" ", 1)[0] + "…"
|
||||
|
||||
|
||||
def render(rec, site):
|
||||
"""Return (title, description, body HTML, needs_map) for one record."""
|
||||
has_map = common.has_line(rec)
|
||||
aside = downloads_panel(rec) + guides_panel(rec) + links_panel(rec)
|
||||
main = (route_block(rec) if common.is_route(rec) else "") + record_block(rec) + verification_block(rec) \
|
||||
+ source_block(rec) + osm_block(rec) + logo_block(rec) + correction_block(rec, site) + raw_record(rec)
|
||||
body = f"""{page_head(rec)}
|
||||
<div class="container detail">
|
||||
{map_figure(rec) if has_map else empty_frame(rec)}
|
||||
<aside class="detail__aside" aria-label="{"Downloads and links" if has_map else "Where to get it, and links"}">
|
||||
{aside}
|
||||
</aside>
|
||||
<div class="detail__main">
|
||||
{main}
|
||||
</div>
|
||||
</div>"""
|
||||
return rec["name"], description(rec), body, has_map
|
||||
|
||||
|
||||
def release_path(repo_root, rec):
|
||||
path = os.path.join(repo_root, rec["id"], "release.txt")
|
||||
return path if os.path.isfile(path) else ""
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Plain words for the record's coded values, and number formatting.
|
||||
|
||||
Every coded value in docs/schema.md that a page shows has a label here, with
|
||||
a one-line meaning taken from the schema or the README.
|
||||
"""
|
||||
from .markup import Markup, esc
|
||||
|
||||
KM_PER_MI = 1.609344
|
||||
|
||||
COUNTRIES = {"US": "United States", "CA": "Canada"}
|
||||
|
||||
US_STATES = {
|
||||
"AK": "Alaska", "AL": "Alabama", "AR": "Arkansas", "AZ": "Arizona", "CA": "California",
|
||||
"CO": "Colorado", "CT": "Connecticut", "DC": "District of Columbia", "DE": "Delaware",
|
||||
"FL": "Florida", "GA": "Georgia", "HI": "Hawaii", "IA": "Iowa", "ID": "Idaho", "IL": "Illinois",
|
||||
"IN": "Indiana", "KS": "Kansas", "KY": "Kentucky", "LA": "Louisiana", "MA": "Massachusetts",
|
||||
"MD": "Maryland", "ME": "Maine", "MI": "Michigan", "MN": "Minnesota", "MO": "Missouri",
|
||||
"MS": "Mississippi", "MT": "Montana", "NC": "North Carolina", "ND": "North Dakota",
|
||||
"NE": "Nebraska", "NH": "New Hampshire", "NJ": "New Jersey", "NM": "New Mexico", "NV": "Nevada",
|
||||
"NY": "New York", "OH": "Ohio", "OK": "Oklahoma", "OR": "Oregon", "PA": "Pennsylvania",
|
||||
"RI": "Rhode Island", "SC": "South Carolina", "SD": "South Dakota", "TN": "Tennessee",
|
||||
"TX": "Texas", "UT": "Utah", "VA": "Virginia", "VT": "Vermont", "WA": "Washington",
|
||||
"WI": "Wisconsin", "WV": "West Virginia", "WY": "Wyoming",
|
||||
}
|
||||
CA_PROVINCES = {
|
||||
"AB": "Alberta", "BC": "British Columbia", "MB": "Manitoba", "NB": "New Brunswick",
|
||||
"NL": "Newfoundland and Labrador", "NS": "Nova Scotia", "NT": "Northwest Territories",
|
||||
"NU": "Nunavut", "ON": "Ontario", "PE": "Prince Edward Island", "QC": "Quebec",
|
||||
"SK": "Saskatchewan", "YT": "Yukon",
|
||||
}
|
||||
ALL_CANADA = "all provinces and territories"
|
||||
|
||||
# (label, meaning). Meanings follow docs/schema.md and README.md.
|
||||
TIERS = {
|
||||
"national": ("National Scenic Trail", "A United States National Scenic Trail"),
|
||||
"regional": ("Regional", "A long trail of 80 km (50 mi) or more"),
|
||||
"short": ("Short", "A well-known multi-day trail of 60 to 80 km"),
|
||||
"deferred": ("Deferred", "Listed, but something about it is not settled; the record's note says what"),
|
||||
"candidate": ("Candidate", "Listing not yet decided"),
|
||||
}
|
||||
WAVES = {
|
||||
"1": ("First set", "In the first set of trails"),
|
||||
"held": ("Held", "Listed, but something about it is not settled"),
|
||||
}
|
||||
INCLUSION = {
|
||||
"nst-unconditional": ("Listed unconditionally", "Every National Scenic Trail is listed"),
|
||||
"candidate-decision-pending": ("Candidate", "The decision to list it is pending"),
|
||||
}
|
||||
KINDS = {
|
||||
"designated": ("Designated trail",
|
||||
"Designated, maintained and published as one trail by a land agency or a trail association"),
|
||||
"route": ("Person-defined route",
|
||||
"Worked out and published by a person or a small group: a high route, a traverse or a loop of linked trails"),
|
||||
}
|
||||
SOURCE_STATUS = {
|
||||
"verified": ("Verified", "The line was downloaded from the source and measured"),
|
||||
"found": ("Found", "The source was located but not downloaded"),
|
||||
"osm-only": ("OpenStreetMap only", "The only source is an OpenStreetMap route relation"),
|
||||
"none": ("None", "No source of a line"),
|
||||
}
|
||||
LICENCES = {
|
||||
"us-gov-public-domain": "US public domain",
|
||||
"CC-BY-4.0": "CC BY 4.0",
|
||||
"CC-BY": "CC BY",
|
||||
"ODbL-1.0": "ODbL 1.0",
|
||||
"CC-BY-NC-ND-4.0": "CC BY-NC-ND 4.0",
|
||||
"none-stated": "None stated",
|
||||
"restricted": "Restricted",
|
||||
"unknown": "Unknown",
|
||||
}
|
||||
LICENCE_URLS = {
|
||||
"us-gov-public-domain": "https://www.usa.gov/government-works",
|
||||
"CC-BY-4.0": "https://creativecommons.org/licenses/by/4.0/",
|
||||
"ODbL-1.0": "https://opendatacommons.org/licenses/odbl/1-0/",
|
||||
"CC-BY-NC-ND-4.0": "https://creativecommons.org/licenses/by-nc-nd/4.0/",
|
||||
}
|
||||
POLICIES = {
|
||||
"open": ("Open", "The creator publishes the line freely",
|
||||
"A line is included only where the creator's terms allow passing it on, or where "
|
||||
"OpenStreetMap carries the route as a route relation. Otherwise get it from the creator."),
|
||||
"sold": ("Sold", "The route is got by buying a guide or map set",
|
||||
"No line is included from any source, OpenStreetMap included."),
|
||||
"withheld": ("Withheld", "The creator chooses not to publish a line",
|
||||
"No line is included from any source, OpenStreetMap included."),
|
||||
"unclear": ("Unclear", "Whether the creator shares the line is not settled",
|
||||
"No line is included until it is settled."),
|
||||
}
|
||||
SHIELD_STATUS = {
|
||||
"use-real-logo": ("Logo in use", "The trail has a logo"),
|
||||
"no-logo-exists": ("No logo", "No logo exists for this trail"),
|
||||
"logo-not-found": ("Logo not found", "No logo file was found"),
|
||||
}
|
||||
ACCESS = {"free": "Free", "purchase": "Purchase"}
|
||||
DECISIONS = {"included-named": "Included with its name"}
|
||||
|
||||
|
||||
def label(table, key):
|
||||
"""The label for a coded value; the raw value itself when the table has none."""
|
||||
entry = table.get(str(key))
|
||||
return entry[0] if isinstance(entry, tuple) else (entry or str(key))
|
||||
|
||||
|
||||
def meaning(table, key):
|
||||
entry = table.get(str(key))
|
||||
return entry[1] if isinstance(entry, tuple) else ""
|
||||
|
||||
|
||||
def region_name(code):
|
||||
if code == ALL_CANADA:
|
||||
return "All provinces and territories"
|
||||
return US_STATES.get(code) or CA_PROVINCES.get(code) or code
|
||||
|
||||
|
||||
def region_country(code):
|
||||
""""US" or "CA" for a state, province or territory code; "CA" for all of Canada; "" when unknown."""
|
||||
if code == ALL_CANADA or code in CA_PROVINCES:
|
||||
return "CA"
|
||||
if code in US_STATES:
|
||||
return "US"
|
||||
return ""
|
||||
|
||||
|
||||
def region_key(code, country):
|
||||
"""Filter value for a region: "US-AZ", "CA-ON"; "CA-*" for all of Canada."""
|
||||
if code == ALL_CANADA:
|
||||
return "CA-*"
|
||||
if code in CA_PROVINCES:
|
||||
return f"CA-{code}"
|
||||
if code in US_STATES:
|
||||
return f"US-{code}"
|
||||
return f"{country}-{code}"
|
||||
|
||||
|
||||
def fmt_int(n):
|
||||
return f"{int(round(n)):,}"
|
||||
|
||||
|
||||
def fmt_km(km):
|
||||
"""1287 -> "1,287"; 1255.1 -> "1,255.1"."""
|
||||
if float(km).is_integer():
|
||||
return f"{int(km):,}"
|
||||
return f"{km:,.1f}"
|
||||
|
||||
|
||||
def fmt_km1(km):
|
||||
"""A measured length, always with one decimal: 2.0 -> "2.0", 1141 -> "1,141.0"."""
|
||||
return f"{float(km):,.1f}"
|
||||
|
||||
|
||||
def km_to_mi(km):
|
||||
return km / KM_PER_MI
|
||||
|
||||
|
||||
def fmt_percent(p):
|
||||
"""-2.5 -> "−2.5%" (true minus sign), 0.9 -> "+0.9%", 0 -> "0.0%"."""
|
||||
if p == 0:
|
||||
return "0.0%"
|
||||
sign = "+" if p > 0 else "−"
|
||||
return f"{sign}{abs(p):.1f}%"
|
||||
|
||||
|
||||
def fmt_bytes(n):
|
||||
if n >= 1_000_000:
|
||||
return f"{n / 1_000_000:.1f} MB"
|
||||
if n >= 1_000:
|
||||
return f"{round(n / 1_000):,} KB"
|
||||
return f"{n} B"
|
||||
|
||||
|
||||
def length(km, style="inline", mi=None, measured=False):
|
||||
"""A length in both units. The reader's unit preference decides the order (CSS).
|
||||
|
||||
style "inline": "1,287 km (800 mi)"; "stack": large first unit over small second.
|
||||
measured: a measured length, always written with its one decimal ("2.0 km").
|
||||
"""
|
||||
mi = km_to_mi(km) if mi is None else mi
|
||||
km_text = f"{fmt_km1(km) if measured else fmt_km(km)} km"
|
||||
whole = float(km).is_integer() and not measured
|
||||
mi_text = f"{fmt_int(mi)} mi" if whole or mi >= 100 else f"{mi:,.1f} mi"
|
||||
return Markup(f'<span class="len len--{style}"><span class="len__km">{esc(km_text)}</span>'
|
||||
f'<span class="len__mi">{esc(mi_text)}</span></span>')
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serve the built site locally with the response headers from _site/_headers applied.
|
||||
|
||||
For checking pages under the production Content-Security-Policy (Netlify
|
||||
applies _headers in production; plain `python3 -m http.server` does not).
|
||||
|
||||
python3 web/serve.py [--dir _site] [--port 8000]
|
||||
"""
|
||||
import argparse
|
||||
import functools
|
||||
import http.server
|
||||
import os
|
||||
import re
|
||||
|
||||
|
||||
def parse_headers(path):
|
||||
"""Netlify _headers file -> [(compiled path pattern, [(name, value), ...])]."""
|
||||
rules = []
|
||||
if not os.path.isfile(path):
|
||||
return rules
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
if not line[0].isspace():
|
||||
pattern = "^" + re.escape(line.strip()).replace(r"\*", ".*") + "$"
|
||||
rules.append((re.compile(pattern), []))
|
||||
elif rules and ":" in line:
|
||||
name, value = line.strip().split(":", 1)
|
||||
rules[-1][1].append((name.strip(), value.strip()))
|
||||
return rules
|
||||
|
||||
|
||||
class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
rules = []
|
||||
|
||||
def _rule_headers(self):
|
||||
path = self.path.split("?", 1)[0].split("#", 1)[0]
|
||||
out = {}
|
||||
for pattern, headers in self.rules:
|
||||
if pattern.match(path):
|
||||
for name, value in headers:
|
||||
out[name.lower()] = (name, value)
|
||||
return out
|
||||
|
||||
def send_header(self, keyword, value):
|
||||
# A Content-Type from _headers replaces the guessed one.
|
||||
if keyword.lower() == "content-type" and "content-type" in self._rule_headers():
|
||||
return
|
||||
super().send_header(keyword, value)
|
||||
|
||||
def end_headers(self):
|
||||
for name, value in self._rule_headers().values():
|
||||
super().send_header(name, value)
|
||||
super().end_headers()
|
||||
|
||||
def send_error(self, code, message=None, explain=None):
|
||||
page = os.path.join(self.directory, "404.html")
|
||||
if code == 404 and os.path.isfile(page):
|
||||
with open(page, "rb") as f:
|
||||
body = f.read()
|
||||
self.send_response(404)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
if self.command != "HEAD":
|
||||
self.wfile.write(body)
|
||||
return
|
||||
super().send_error(code, message, explain)
|
||||
|
||||
|
||||
def main():
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("--dir", default=os.path.join(root, "_site"))
|
||||
ap.add_argument("--port", type=int, default=8000)
|
||||
args = ap.parse_args()
|
||||
Handler.rules = parse_headers(os.path.join(args.dir, "_headers"))
|
||||
handler = functools.partial(Handler, directory=args.dir)
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", args.port), handler) as httpd:
|
||||
print(f"serving {args.dir} at http://127.0.0.1:{args.port}/ with {len(Handler.rules)} header rules")
|
||||
httpd.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,31 @@
|
||||
# Site-wide settings for the generated pages. Read by web/olt/site.py.
|
||||
#
|
||||
# The site's display name appears only here: every page, title and footer
|
||||
# takes it from `name`, so a rename is a one-line change.
|
||||
|
||||
name = "Long Hikes"
|
||||
|
||||
# One line under the name: the home page <title> and the default meta description.
|
||||
tagline = "Long-distance hiking trails of the United States and Canada, with their lines where they may be shared"
|
||||
|
||||
# Absolute origin of the deployed site, without a trailing slash, for example
|
||||
# "https://example.org". When set, every page gets a canonical link. Empty: none.
|
||||
base_url = "https://longhikes.org"
|
||||
|
||||
# Home of the source repository, for example "https://github.com/owner/repo".
|
||||
# When set, pages link to it for reporting an error. Empty: those links are left out.
|
||||
repo_url = ""
|
||||
|
||||
# Where to write to the maintainers (a contact page or a mailto: address), for
|
||||
# logo removal requests and other questions. When this or repo_url is set, the
|
||||
# About and Logos pages link the documents' "open an issue" and "write to the
|
||||
# maintainers" wording to it. Empty: the documents' wording is left as it is.
|
||||
contact_url = ""
|
||||
|
||||
# Language of record names that are not English, by record id (a BCP 47 tag).
|
||||
# Every place a page shows one of these names as text marks it with lang="..",
|
||||
# so screen readers pronounce it in that language.
|
||||
[name_lang]
|
||||
traversee-charlevoix = "fr"
|
||||
sentier-national = "fr"
|
||||
sentier-international-appalaches = "fr"
|
||||
@@ -0,0 +1,94 @@
|
||||
# Netlify response headers. web/build.py copies web/static/ verbatim into the
|
||||
# publish root, so this file is deployed as _site/_headers.
|
||||
#
|
||||
# Syntax and wildcard rules (checked 2026-11-10):
|
||||
# https://docs.netlify.com/manage/routing/headers/
|
||||
# Wildcards (*) are allowed anywhere inside a path segment ("*.gpx" is valid)
|
||||
# and match any characters; every rule whose path matches a request applies.
|
||||
# Trail downloads live at /trails/<id>/<name>, one directory below /trails/,
|
||||
# so both segments are matched explicitly rather than relying on * to span the
|
||||
# slash.
|
||||
#
|
||||
# No two rules set the same header for the same path: when rules overlap,
|
||||
# Netlify applies all of them, so each header is set by one rule only
|
||||
# (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).
|
||||
/*
|
||||
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'
|
||||
|
||||
# Site data. Matched by file type, not /data/*, so the pages under /data/
|
||||
# (/data/, /data/schema/, /data/changelog/) revalidate like every other page.
|
||||
# overview.geojson and trails.json are fetched by page scripts; index.geojson,
|
||||
# trails.csv and the two archives are downloads.
|
||||
/data/*.json
|
||||
Cache-Control: public, max-age=300, must-revalidate
|
||||
|
||||
/data/*.geojson
|
||||
Cache-Control: public, max-age=300, must-revalidate
|
||||
|
||||
/data/*.csv
|
||||
Cache-Control: public, max-age=300, must-revalidate
|
||||
|
||||
/data/*.zip
|
||||
Content-Type: application/zip
|
||||
Content-Disposition: attachment
|
||||
Cache-Control: public, max-age=300, must-revalidate
|
||||
|
||||
/data/overview.geojson
|
||||
Content-Type: application/geo+json
|
||||
|
||||
/data/trails.json
|
||||
Content-Type: application/json
|
||||
|
||||
/data/index.geojson
|
||||
Content-Type: application/geo+json
|
||||
Content-Disposition: attachment
|
||||
|
||||
/data/trails.csv
|
||||
Content-Type: text/csv; charset=utf-8
|
||||
Content-Disposition: attachment
|
||||
|
||||
# HTML revalidates before reuse. Netlify's default for static assets is already
|
||||
# "public, max-age=0, must-revalidate" (which also covers clean URLs served
|
||||
# from index.html); this makes the intent explicit for .html requests.
|
||||
/*.html
|
||||
Cache-Control: public, max-age=0, must-revalidate
|
||||
|
||||
# Self-hosted MapLibre CSS/JS is not fingerprinted yet, so keep it short.
|
||||
/assets/*
|
||||
Cache-Control: public, max-age=300, must-revalidate
|
||||
|
||||
# Trail downloads: correct media types and a download disposition.
|
||||
/trails/*/*.gpx
|
||||
Content-Type: application/gpx+xml
|
||||
Content-Disposition: attachment
|
||||
Cache-Control: public, max-age=3600
|
||||
|
||||
/trails/*/*.geojson
|
||||
Content-Type: application/geo+json
|
||||
Content-Disposition: attachment
|
||||
Cache-Control: public, max-age=3600
|
||||
|
||||
# Map geometry for the trail pages: fetched by page scripts, never a download.
|
||||
/trails/*/map.json
|
||||
Content-Type: application/json
|
||||
Cache-Control: public, max-age=300, must-revalidate
|
||||
|
||||
# Record and release notes: shown in the browser, not downloaded.
|
||||
/trails/*/trail.toml
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
|
||||
/trails/*/release.txt
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
|
||||
# Licence texts (LICENSE has no extension): shown in the browser as text.
|
||||
/licences/*
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
@@ -0,0 +1,265 @@
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import build # noqa: E402
|
||||
|
||||
|
||||
class CopyStaticTest(unittest.TestCase):
|
||||
def test_copies_tree_verbatim(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
static = os.path.join(tmp, "static")
|
||||
out = os.path.join(tmp, "out")
|
||||
contents = {
|
||||
"_headers": "/*\n X-Content-Type-Options: nosniff\n",
|
||||
os.path.join("assets", "site.css"): "body { margin: 0 }\n",
|
||||
os.path.join("assets", "sub", "app.js"): "0;\n",
|
||||
}
|
||||
for rel, text in contents.items():
|
||||
path = os.path.join(static, rel)
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
os.makedirs(out)
|
||||
|
||||
stats = build.Stats()
|
||||
build.copy_static(static, out, stats)
|
||||
|
||||
self.assertEqual(stats.written, len(contents))
|
||||
for rel, text in contents.items():
|
||||
with open(os.path.join(out, rel), encoding="utf-8") as f:
|
||||
self.assertEqual(f.read(), text)
|
||||
|
||||
def test_missing_static_dir_is_skipped(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = os.path.join(tmp, "out")
|
||||
os.makedirs(out)
|
||||
stats = build.Stats()
|
||||
build.copy_static(os.path.join(tmp, "nonexistent"), out, stats)
|
||||
self.assertEqual(stats.written, 0)
|
||||
self.assertEqual(os.listdir(out), [])
|
||||
|
||||
def test_cache_is_outside_the_publish_directory(self):
|
||||
# The cache lives beside build.py, under web/, not under _site.
|
||||
self.assertEqual(build.CACHE_DIR, os.path.join(build.HERE, ".cache"))
|
||||
|
||||
|
||||
REAL_ROOT = build.ROOT
|
||||
SMALL = ("batona", "avon", "canol")
|
||||
|
||||
|
||||
class FakePages:
|
||||
"""Stands in for olt.pages: records what render_site was given."""
|
||||
calls = []
|
||||
|
||||
@classmethod
|
||||
def render_site(cls, recs, out_dir, root):
|
||||
cls.calls.append([r["id"] for r in recs])
|
||||
|
||||
|
||||
class BuildTreeTest(unittest.TestCase):
|
||||
"""Builds a few real trail directories into a throwaway tree."""
|
||||
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = os.path.join(tmp.name, "repo")
|
||||
self.out = os.path.join(tmp.name, "site")
|
||||
os.makedirs(self.root)
|
||||
for tid in SMALL:
|
||||
shutil.copytree(os.path.join(REAL_ROOT, tid), os.path.join(self.root, tid))
|
||||
for name in ("trails.csv", "index.geojson"):
|
||||
shutil.copyfile(os.path.join(REAL_ROOT, name), os.path.join(self.root, name))
|
||||
FakePages.calls = []
|
||||
for p in (mock.patch.object(build, "ROOT", self.root),
|
||||
mock.patch.object(build, "CACHE_DIR", os.path.join(tmp.name, "cache")),
|
||||
mock.patch.object(build, "import_pages", lambda: FakePages)):
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def build(self, *extra):
|
||||
err = io.StringIO()
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err):
|
||||
build.main(["--out", self.out, *extra])
|
||||
return err.getvalue()
|
||||
|
||||
def path(self, *parts):
|
||||
return os.path.join(self.out, *parts)
|
||||
|
||||
def trails_json(self):
|
||||
with open(self.path("data", "trails.json"), encoding="utf-8") as f:
|
||||
return {r["id"]: r for r in json.load(f)}
|
||||
|
||||
def overview_ids(self):
|
||||
with open(self.path("data", "overview.geojson"), encoding="utf-8") as f:
|
||||
return sorted(ft["properties"]["id"] for ft in json.load(f)["features"])
|
||||
|
||||
def add_alternates(self, tid):
|
||||
with open(os.path.join(self.root, tid, "line.geojson"), encoding="utf-8") as f:
|
||||
parts = build.geo.parts_from_geojson(json.load(f))
|
||||
alt = {"type": "Feature", "properties": {},
|
||||
"geometry": {"type": "MultiLineString", "coordinates": parts[:1]}}
|
||||
with open(os.path.join(self.root, tid, "alternates.geojson"), "w", encoding="utf-8") as f:
|
||||
json.dump(alt, f)
|
||||
|
||||
def map_roles(self, tid):
|
||||
with open(self.path("trails", tid, "map.json"), encoding="utf-8") as f:
|
||||
return [ft["properties"]["role"] for ft in json.load(f)["features"]]
|
||||
|
||||
def test_deleted_line_file_removes_outputs_and_cache(self):
|
||||
self.add_alternates("batona")
|
||||
self.build()
|
||||
self.assertEqual(self.map_roles("batona"), ["main", "alternate"])
|
||||
self.assertIn("bbox", self.trails_json()["batona"]["derived"])
|
||||
os.remove(os.path.join(self.root, "batona", "line.geojson"))
|
||||
warnings = self.build()
|
||||
self.assertIn("batona", warnings)
|
||||
tdir = self.path("trails", "batona")
|
||||
self.assertFalse(os.path.exists(os.path.join(tdir, "batona.geojson")))
|
||||
self.assertFalse(os.path.exists(os.path.join(tdir, "batona.gpx")))
|
||||
self.assertEqual(self.map_roles("batona"), ["alternate"])
|
||||
derived = self.trails_json()["batona"]["derived"]
|
||||
self.assertNotIn("bbox", derived)
|
||||
self.assertEqual([d["role"] for d in derived["downloads"]], ["alternates"] * 2)
|
||||
self.assertNotIn("batona", self.overview_ids())
|
||||
|
||||
os.remove(os.path.join(self.root, "batona", "alternates.geojson"))
|
||||
self.build()
|
||||
self.assertEqual(sorted(os.listdir(tdir)), [])
|
||||
self.assertEqual(self.trails_json()["batona"]["derived"]["downloads"], [])
|
||||
|
||||
def test_pages_files_survive_cleanup(self):
|
||||
self.build()
|
||||
tdir = self.path("trails", "avon")
|
||||
for name in ("index.html", "trail.toml", "release.txt"):
|
||||
with open(os.path.join(tdir, name), "w") as f:
|
||||
f.write("x")
|
||||
os.remove(os.path.join(self.root, "avon", "line.geojson"))
|
||||
self.build()
|
||||
self.assertEqual(sorted(os.listdir(tdir)), ["index.html", "release.txt", "trail.toml"])
|
||||
|
||||
def test_removed_trail_directory_is_pruned(self):
|
||||
self.build()
|
||||
shutil.rmtree(os.path.join(self.root, "canol"))
|
||||
self.build("--only", "avon")
|
||||
self.assertTrue(os.path.isdir(self.path("trails", "canol"))) # --only never prunes
|
||||
self.build()
|
||||
self.assertFalse(os.path.exists(self.path("trails", "canol")))
|
||||
self.assertTrue(os.path.isdir(self.path("trails", "avon")))
|
||||
self.assertNotIn("canol", self.trails_json())
|
||||
|
||||
def test_only_keeps_site_wide_data_complete(self):
|
||||
self.build()
|
||||
full_ids = sorted(self.trails_json())
|
||||
overview = self.overview_ids()
|
||||
self.assertEqual(full_ids, sorted(SMALL))
|
||||
self.build("--only", "avon")
|
||||
self.assertEqual(sorted(self.trails_json()), full_ids)
|
||||
self.assertEqual(self.overview_ids(), overview)
|
||||
self.assertEqual(FakePages.calls[-1], sorted(SMALL))
|
||||
# a non-selected trail with no cache entry is built, not dropped
|
||||
shutil.rmtree(build.CACHE_DIR)
|
||||
self.build("--only", "avon")
|
||||
self.assertEqual(self.overview_ids(), overview)
|
||||
self.assertIn("bbox", self.trails_json()["batona"]["derived"])
|
||||
|
||||
def test_empty_feature_collection_is_no_line(self):
|
||||
self.build()
|
||||
with open(os.path.join(self.root, "batona", "line.geojson"), "w") as f:
|
||||
json.dump({"type": "FeatureCollection", "features": []}, f)
|
||||
warnings = self.build()
|
||||
self.assertEqual(len(warnings.splitlines()), 1)
|
||||
self.assertIn("batona", warnings)
|
||||
tdir = self.path("trails", "batona")
|
||||
self.assertEqual([n for n in os.listdir(tdir) if n.endswith((".json", ".gpx", ".geojson"))], [])
|
||||
derived = self.trails_json()["batona"]["derived"]
|
||||
self.assertEqual(derived["downloads"], [])
|
||||
self.assertNotIn("batona", self.overview_ids())
|
||||
self.assertIn("avon", self.overview_ids())
|
||||
|
||||
def test_collapsed_line_after_rounding_is_no_line(self):
|
||||
self.build()
|
||||
with mock.patch.object(build.geo, "round_coords", lambda parts, decimals: []):
|
||||
warnings = self.build("--force")
|
||||
self.assertIn("batona", warnings)
|
||||
self.assertFalse(os.path.exists(self.path("trails", "batona", "map.json")))
|
||||
|
||||
def test_map_bbox_contains_every_written_coordinate(self):
|
||||
self.build()
|
||||
for tid in SMALL:
|
||||
with open(self.path("trails", tid, "map.json"), encoding="utf-8") as f:
|
||||
fc = json.load(f)
|
||||
w, s, e, n = fc["bbox"]
|
||||
for ft in fc["features"]:
|
||||
for part in ft["geometry"]["coordinates"]:
|
||||
for c in part:
|
||||
self.assertTrue(w <= c[0] <= e and s <= c[1] <= n, (tid, c, fc["bbox"]))
|
||||
|
||||
def test_bbox_is_computed_from_rounded_coordinates(self):
|
||||
# 0.0000004 rounds to 0: the source box would poke past the published line.
|
||||
line = {"type": "Feature", "properties": {}, "geometry": {
|
||||
"type": "LineString", "coordinates": [[0.0000004, 0.0000004], [1.0000004, 1.0000004]]}}
|
||||
with open(os.path.join(self.root, "avon", "line.geojson"), "w") as f:
|
||||
json.dump(line, f)
|
||||
self.build()
|
||||
with open(self.path("trails", "avon", "map.json"), encoding="utf-8") as f:
|
||||
self.assertEqual(json.load(f)["bbox"], [0.0, 0.0, 1.0, 1.0])
|
||||
|
||||
def test_unchanged_tree_is_up_to_date(self):
|
||||
self.build()
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
|
||||
build.main(["--out", self.out])
|
||||
self.assertIn("trails processed 0", out.getvalue())
|
||||
|
||||
def test_archives_rebuilt_only_when_an_input_is_newer(self):
|
||||
self.build()
|
||||
gpx, geojson = self.path("data", "all-gpx.zip"), self.path("data", "all-geojson.zip")
|
||||
with zipfile.ZipFile(gpx) as zf:
|
||||
names = zf.namelist()
|
||||
readme = zf.read("README.txt").decode("utf-8")
|
||||
self.assertEqual(names[0], "README.txt")
|
||||
for tid in SMALL:
|
||||
self.assertIn(f"{tid}/{tid}.gpx", names)
|
||||
self.assertIn(f"{tid}/release.txt", names)
|
||||
self.assertIn("trails.csv", names)
|
||||
self.assertIn("5 m", readme)
|
||||
with zipfile.ZipFile(geojson) as zf:
|
||||
self.assertIn("avon/avon.geojson", zf.namelist())
|
||||
self.assertIsNone(zf.testzip())
|
||||
stamps = (os.path.getmtime(gpx), os.path.getmtime(geojson))
|
||||
self.build()
|
||||
self.assertEqual((os.path.getmtime(gpx), os.path.getmtime(geojson)), stamps)
|
||||
# a trail gone from the dataset is gone from the archives, though no input is newer
|
||||
shutil.rmtree(os.path.join(self.root, "canol"))
|
||||
self.build()
|
||||
with zipfile.ZipFile(gpx) as zf:
|
||||
self.assertFalse(any(n.startswith("canol/") for n in zf.namelist()))
|
||||
stamps = (os.path.getmtime(gpx), os.path.getmtime(geojson))
|
||||
self.build()
|
||||
self.assertEqual((os.path.getmtime(gpx), os.path.getmtime(geojson)), stamps)
|
||||
# a newer input (here a release.txt) rebuilds both archives
|
||||
later = max(stamps) + 10
|
||||
os.utime(os.path.join(self.root, "avon", "release.txt"), (later, later))
|
||||
self.build()
|
||||
self.assertNotEqual(os.path.getmtime(gpx), stamps[0])
|
||||
self.assertNotEqual(os.path.getmtime(geojson), stamps[1])
|
||||
|
||||
def test_missing_declared_line_warns(self):
|
||||
os.remove(os.path.join(self.root, "avon", "line.geojson"))
|
||||
warnings = self.build()
|
||||
self.assertIn("avon", warnings)
|
||||
self.assertEqual(self.trails_json()["avon"]["derived"]["downloads"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,334 @@
|
||||
"""Tests for the added pages: regions, routes, sources, logos, about, data, SEO files,
|
||||
the bulk archives and the response headers."""
|
||||
import html
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
import serve # noqa: E402
|
||||
from olt import docs, home, records, regions as regions_mod, seo, site, words # noqa: E402
|
||||
|
||||
OUT = os.path.join(WEB, ".cache", "test-site")
|
||||
|
||||
|
||||
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_out(relpath):
|
||||
with open(os.path.join(OUT, *relpath.split("/")), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def entry_ids(doc):
|
||||
return re.findall(r'<li class="entry" data-id="([^"]+)"', doc)
|
||||
|
||||
|
||||
class ExtraPagesTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.records = records.load_records(ROOT)
|
||||
|
||||
def test_every_region_code_has_a_page(self):
|
||||
codes = {c for r in self.records for c in r.get("regions", [])
|
||||
if c != words.ALL_CANADA}
|
||||
for code in codes:
|
||||
slug = words.region_key(code, "US").lower()
|
||||
path = os.path.join(OUT, "regions", slug, "index.html")
|
||||
self.assertTrue(os.path.isfile(path), f"{code} -> {slug}")
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, "regions", "index.html")))
|
||||
|
||||
def test_each_record_on_each_region_page(self):
|
||||
for rec in self.records:
|
||||
for code in rec.get("regions", []):
|
||||
if code == words.ALL_CANADA:
|
||||
page = read_out("regions/index.html")
|
||||
else:
|
||||
slug = words.region_key(code, rec["country"]).lower()
|
||||
page = read_out(f"regions/{slug}/index.html")
|
||||
self.assertIn(f'href="/trails/{rec["id"]}/"', page, f'{rec["id"]} in {code}')
|
||||
|
||||
def test_all_routes_on_routes_page(self):
|
||||
routes = [r for r in self.records if r["derived"]["kind"] == "route"]
|
||||
self.assertEqual(len(routes), 34)
|
||||
page = read_out("routes/index.html")
|
||||
import html as _html
|
||||
text = _html.unescape(page)
|
||||
for r in routes:
|
||||
self.assertIn(f'href="/trails/{r["id"]}/"', page, r["id"])
|
||||
self.assertIn(r["route"]["creator"], text, r["id"])
|
||||
|
||||
def test_every_logo_on_logos_page(self):
|
||||
page = read_out("logos/index.html")
|
||||
for r in self.records:
|
||||
if "shield" in r["derived"]["files"]:
|
||||
self.assertIn(f'href="/trails/{r["id"]}/"', page, r["id"])
|
||||
self.assertIn("no-logo-exists", page)
|
||||
self.assertIn("logo-not-found", page)
|
||||
|
||||
def test_added_pages_exist(self):
|
||||
for rel in ("sources/index.html", "about/index.html", "data/index.html",
|
||||
"data/schema/index.html", "data/changelog/index.html",
|
||||
"licences/LICENSE", "licences/MIT.txt", "robots.txt"):
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *rel.split("/"))), rel)
|
||||
|
||||
def test_no_dead_internal_links_in_added_pages(self):
|
||||
import re
|
||||
for rel in ("regions/index.html", "routes/index.html", "sources/index.html",
|
||||
"logos/index.html", "about/index.html", "data/index.html",
|
||||
"data/schema/index.html", "data/changelog/index.html"):
|
||||
html = read_out(rel)
|
||||
for url in re.findall(r'(?:href|src)="(/[^"]*)"', html):
|
||||
path = url.split("#", 1)[0].split("?", 1)[0]
|
||||
if not path:
|
||||
continue
|
||||
if path.endswith("/"):
|
||||
path += "index.html"
|
||||
target = os.path.join(OUT, *path.lstrip("/").split("/"))
|
||||
self.assertTrue(os.path.isfile(target), f"{rel} -> {url}")
|
||||
|
||||
def test_region_map_limited_to_region_ids(self):
|
||||
page = read_out("regions/us-vt/index.html")
|
||||
self.assertIn('data-map="overview"', page)
|
||||
self.assertIn("data-ids=", page)
|
||||
self.assertIn("long-trail", page)
|
||||
|
||||
def test_home_region_links_point_to_region_pages(self):
|
||||
page = read_out("index.html")
|
||||
self.assertIn('href="/regions/us-vt/"', page)
|
||||
|
||||
|
||||
def test_country_and_region_counts_match_the_regions_pages(self):
|
||||
home_doc = read_out("index.html")
|
||||
index = read_out("regions/index.html")
|
||||
by_slug, canada_wide = regions_mod.collect_regions(self.records)
|
||||
for country, label in (("US", "United States"), ("CA", "Canada")):
|
||||
shown = int(re.search(rf'value="{country}"><span>{label} \((\d+)\)</span>', home_doc).group(1))
|
||||
on_index = int(re.search(rf'data-country-count="{country}">(\d+)<', index).group(1))
|
||||
listed = set()
|
||||
for slug, info in by_slug.items():
|
||||
if info["country"] == country:
|
||||
listed |= set(entry_ids(read_out(f"regions/{slug}/index.html")))
|
||||
if country == "CA":
|
||||
listed |= {r["id"] for r in canada_wide}
|
||||
self.assertEqual(shown, on_index, country)
|
||||
self.assertEqual(shown, len(listed), country)
|
||||
# every row of those records says it touches the country
|
||||
for tid in listed:
|
||||
attrs = re.search(rf'<li class="entry" data-id="{tid}"([^>]*)>', home_doc).group(1)
|
||||
self.assertIn(country, re.search(r'data-countries="([^"]*)"', attrs).group(1).split(), tid)
|
||||
self.assertIn('data-countries="US CA"', re.search(
|
||||
r'<li class="entry" data-id="eastern-continental-trail"[^>]*>', home_doc).group(0))
|
||||
self.assertIn('data-countries="US CA"', re.search(
|
||||
r'<li class="entry" data-id="great-plains-trail"[^>]*>', home_doc).group(0))
|
||||
# each region option's count is the number of records on that region's page
|
||||
for value, n in re.findall(r'<option value="((?:US|CA)-[A-Z]{2})">[^<(]+\((\d+)\)</option>', home_doc):
|
||||
page = read_out(f"regions/{value.lower()}/index.html")
|
||||
self.assertEqual(int(n), len(entry_ids(page)), value)
|
||||
canada = re.search(r'<option value="CA-\*">All provinces and territories \((\d+)\)</option>', home_doc)
|
||||
self.assertEqual(int(canada.group(1)), len(canada_wide))
|
||||
self.assertIn('href="/?region=CA-*"', index)
|
||||
|
||||
def test_list_pages_share_the_home_list(self):
|
||||
for rel in ("index.html", "regions/us-co/index.html", "routes/index.html"):
|
||||
doc = read_out(rel)
|
||||
results = doc[doc.index('<div class="results">'):]
|
||||
for part in ('<div class="list-head" aria-hidden="true">', '<ol class="entries"',
|
||||
'name="units-list"', '<ul class="key"'):
|
||||
self.assertIn(part, results, f"{rel}: {part}")
|
||||
scale = re.search(r'<div class="list-head".*?</div>', results, re.S).group(0)
|
||||
self.assertEqual(scale.count('class="len__km"'), 3, rel)
|
||||
self.assertEqual(scale.count('class="len__mi"'), 3, rel)
|
||||
self.assertNotIn('class="route-item"', read_out("routes/index.html"))
|
||||
co = read_out("regions/us-co/index.html")
|
||||
self.assertIn('<a href="/?region=US-CO&line=1">With a line</a>', co)
|
||||
|
||||
def test_routes_page_rows_carry_their_guides(self):
|
||||
doc = read_out("routes/index.html")
|
||||
routes = [r for r in self.records if r["derived"]["kind"] == "route"]
|
||||
self.assertEqual(sorted(entry_ids(doc)), sorted(r["id"] for r in routes))
|
||||
for r in routes:
|
||||
row = re.search(rf'<li class="entry" data-id="{r["id"]}".*?\n</li>', doc, re.S).group(0)
|
||||
for g in r["guide"]:
|
||||
self.assertIn(f'href="{html.escape(g["url"], quote=True)}"', row, r["id"])
|
||||
|
||||
def test_home_finder_layout(self):
|
||||
doc = read_out("index.html")
|
||||
form = doc[doc.index('<form class="filters"'):doc.index("</form>")]
|
||||
self.assertIn('<details class="filters__more">', form)
|
||||
self.assertNotIn("filters__more\" open", form)
|
||||
# the line checkbox comes straight after the search field, outside the details
|
||||
self.assertLess(form.index('name="line"'), form.index("<details"))
|
||||
self.assertLess(form.index('id="q"'), form.index('name="line"'))
|
||||
self.assertIn('<a class="button button--primary hero__cta" href="#q">Find a trail</a>', doc)
|
||||
self.assertIn("No records match these filters.", doc)
|
||||
steps = [int(v) for v in re.findall(r'<option value="(\d+)">', form[form.index('id="max"'):])]
|
||||
self.assertGreaterEqual(steps[-1], max(r["length_km"] for r in self.records))
|
||||
self.assertEqual(home.length_steps(self.records)[:11], list(home.LENGTH_STEPS))
|
||||
|
||||
def test_logos_page_shows_exactly_the_logo_files(self):
|
||||
page = read_out("logos/index.html")
|
||||
files = sorted(d for d in os.listdir(ROOT)
|
||||
if any(os.path.isfile(os.path.join(ROOT, d, n)) for n in records.SHIELD_NAMES))
|
||||
cards = re.findall(r'<li class="logo-card">.*?<h3><a href="/trails/([^/]+)/">', page, re.S)
|
||||
self.assertEqual(sorted(cards), files)
|
||||
for img in re.findall(r'<li class="logo-card">\s*<div class="plate[^"]*">(.*?)</div>', page, re.S):
|
||||
self.assertIn('alt=""', img)
|
||||
self.assertIn('class="vh"', img) # the link around the image still has a name
|
||||
|
||||
def test_sources_page_counts_measured_lines(self):
|
||||
page = read_out("sources/index.html")
|
||||
measured = sum(1 for r in self.records if r.get("verification", {}).get("verified"))
|
||||
self.assertIn(f"<dt>Line measured</dt><dd>{measured}<", page)
|
||||
self.assertIn("<dt>Source status: OpenStreetMap only</dt>", page)
|
||||
self.assertEqual(page.count('<th scope="col">Trails and routes</th>'), 2)
|
||||
self.assertNotRegex(page, r'<td><a href="/trails/[^"]+/">[^<]*</a>, <a')
|
||||
|
||||
def test_data_page_licences_from_the_records(self):
|
||||
page = read_out("data/index.html")
|
||||
self.assertNotIn("Pacific Crest line (PCTA)", page)
|
||||
lines = [r for r in self.records if r["derived"]["has_line"]]
|
||||
for lic in {r["source"]["licence"] for r in lines}:
|
||||
n = sum(1 for r in lines if r["source"]["licence"] == lic)
|
||||
label = html.escape(words.label(words.LICENCES, lic), quote=True)
|
||||
self.assertIn(f"Lines licensed {label}: {n} record", page, lic)
|
||||
for name in ("trails.json", "overview.geojson"):
|
||||
self.assertRegex(page, rf'<a href="/data/{re.escape(name)}">')
|
||||
for name in ("all-gpx.zip", "all-geojson.zip"):
|
||||
size = words.fmt_bytes(os.path.getsize(os.path.join(OUT, "data", name)))
|
||||
self.assertRegex(page, rf'/data/{re.escape(name)}</a></td><td>[^<]*</td><td class="num">{re.escape(size)}<')
|
||||
self.assertIn(f'"contentUrl":"{site.load().base_url}/data/{name}"', page)
|
||||
|
||||
def test_archives_hold_every_line(self):
|
||||
lines = [r for r in self.records if r["derived"]["has_line"]]
|
||||
for name, ext in (("all-gpx.zip", ".gpx"), ("all-geojson.zip", ".geojson")):
|
||||
with zipfile.ZipFile(os.path.join(OUT, "data", name)) as zf:
|
||||
names = set(zf.namelist())
|
||||
for doc in ("README.txt", "trails.csv", "SOURCES.md"):
|
||||
self.assertIn(doc, names, name)
|
||||
for r in lines:
|
||||
self.assertIn(f'{r["id"]}/{r["id"]}{ext}', names, name)
|
||||
self.assertIn(f'{r["id"]}/release.txt', names, name)
|
||||
if "alternates" in r["derived"]["files"]:
|
||||
self.assertIn(f'{r["id"]}/{r["id"]}-alternates{ext}', names, name)
|
||||
self.assertTrue(all(n.endswith((ext, "release.txt")) or "/" not in n for n in names), name)
|
||||
readme = zf.read("README.txt").decode("utf-8")
|
||||
self.assertIn("release.txt", readme)
|
||||
self.assertIn("trails.csv", readme)
|
||||
self.assertIn("5 m", readme)
|
||||
if ext == ".gpx":
|
||||
self.assertIsNone(zf.testzip())
|
||||
info = zf.getinfo(f"{lines[0]['id']}/{lines[0]['id']}.gpx")
|
||||
self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
|
||||
|
||||
def test_document_requests_link_only_when_configured(self):
|
||||
text = ("<p>Open an issue, or send a patch.</p><p>Ask by opening an issue in this repository, "
|
||||
"or by writing to the repository maintainers through the contact.</p>")
|
||||
self.assertEqual(docs.link_requests(text, site.Site("N", "T")), text)
|
||||
out = docs.link_requests(text, site.Site("N", "T", repo_url="https://example.org/r"))
|
||||
self.assertIn('<a href="https://example.org/r/issues">Open an issue</a>', out)
|
||||
self.assertIn('<a href="https://example.org/r/issues">opening an issue</a>', out)
|
||||
self.assertIn('<a href="https://example.org/r">writing to the repository maintainers</a>', out)
|
||||
out = docs.link_requests(text, site.Site("N", "T", contact_url="mailto:a@example.org"))
|
||||
self.assertIn('<a href="mailto:a@example.org">writing to the repository maintainers</a>', out)
|
||||
self.assertIn('<a href="mailto:a@example.org">Open an issue</a>', out)
|
||||
configured = site.load()
|
||||
if not (configured.repo_url or configured.contact_url): # left as the documents have it
|
||||
self.assertIn("<p>Open an issue, or send a patch", read_out("about/index.html"))
|
||||
self.assertIn(" by opening an issue in this repository, or by writing to the repository maintainers ",
|
||||
read_out("logos/index.html"))
|
||||
|
||||
|
||||
class HeadersTest(unittest.TestCase):
|
||||
"""The built _headers, read the way serve.py applies it, over every file in the built site."""
|
||||
NETLIFY_DEFAULT_CACHE = "public, max-age=0, must-revalidate" # when no rule sets Cache-Control
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.rules = serve.parse_headers(os.path.join(OUT, "_headers"))
|
||||
cls.paths = []
|
||||
for base, _, names in os.walk(OUT):
|
||||
for n in names:
|
||||
cls.paths.append("/" + os.path.relpath(os.path.join(base, n), OUT).replace(os.sep, "/"))
|
||||
|
||||
def headers(self, path):
|
||||
"""{lower name: value}, failing when two matching rules set the same header."""
|
||||
out = {}
|
||||
for pattern, headers in self.rules:
|
||||
if pattern.match(path):
|
||||
for name, value in headers:
|
||||
self.assertNotIn(name.lower(), out, f"{path}: {name} set by two rules")
|
||||
out[name.lower()] = value
|
||||
return out
|
||||
|
||||
def test_pages_revalidate(self):
|
||||
pages = [p for p in self.paths if p.endswith(".html")]
|
||||
self.assertGreater(len(pages), 200)
|
||||
clean = [p[:-len("index.html")] for p in pages if p.endswith("/index.html")]
|
||||
for path in pages + clean:
|
||||
cache = self.headers(path).get("cache-control", self.NETLIFY_DEFAULT_CACHE)
|
||||
self.assertIn("max-age=0", cache, path)
|
||||
for path in ("/data/", "/data/index.html", "/data/schema/", "/data/changelog/"):
|
||||
self.assertIn("max-age=0", self.headers(path).get("cache-control", self.NETLIFY_DEFAULT_CACHE), path)
|
||||
|
||||
def test_line_files_and_licences_get_their_types(self):
|
||||
seen = {".gpx": 0, ".geojson": 0}
|
||||
for path in self.paths:
|
||||
h = self.headers(path)
|
||||
if path.startswith("/trails/") and path.endswith(".gpx"):
|
||||
seen[".gpx"] += 1
|
||||
self.assertEqual(h.get("content-type"), "application/gpx+xml", path)
|
||||
elif path.startswith("/trails/") and path.endswith(".geojson"):
|
||||
seen[".geojson"] += 1
|
||||
self.assertEqual(h.get("content-type"), "application/geo+json", path)
|
||||
elif path.startswith("/data/") and path.endswith(".zip"):
|
||||
self.assertEqual(h.get("content-type"), "application/zip", path)
|
||||
self.assertGreater(seen[".gpx"], 85)
|
||||
self.assertGreater(seen[".geojson"], 85)
|
||||
self.assertEqual(self.headers("/licences/LICENSE").get("content-type"), "text/plain; charset=utf-8")
|
||||
self.assertIn("/licences/LICENSE", self.paths)
|
||||
|
||||
def test_fonts_are_same_origin(self):
|
||||
csp = self.headers("/").get("content-security-policy", "")
|
||||
font_src = re.search(r"font-src ([^;]*)", csp).group(1)
|
||||
self.assertEqual(font_src.strip(), "'self'")
|
||||
self.assertIn("https://tiles.openfreemap.org", re.search(r"connect-src ([^;]*)", csp).group(1))
|
||||
|
||||
|
||||
class SeoTest(unittest.TestCase):
|
||||
def test_sitemap_absent_without_base_url(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
seo.write_seo_files(tmp, ["/"], site.Site("N", "T"))
|
||||
self.assertFalse(os.path.exists(os.path.join(tmp, "sitemap.xml")))
|
||||
with open(os.path.join(tmp, "robots.txt"), encoding="utf-8") as f:
|
||||
self.assertNotIn("Sitemap:", f.read())
|
||||
|
||||
def test_sitemap_complete_with_base_url(self):
|
||||
import tempfile
|
||||
recs = records.load_records(ROOT)
|
||||
by_slug, _ = regions_mod.collect_regions(recs)
|
||||
region_paths = [f"/regions/{s}/" for s in sorted(by_slug)]
|
||||
paths = seo.all_paths(recs, region_paths)
|
||||
s = site.Site("N", "T", base_url="https://example.org")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
seo.write_seo_files(tmp, paths, s)
|
||||
with open(os.path.join(tmp, "sitemap.xml"), encoding="utf-8") as f:
|
||||
xml = f.read()
|
||||
for p in paths:
|
||||
self.assertIn(f"<loc>https://example.org{p}</loc>", xml, p)
|
||||
with open(os.path.join(tmp, "robots.txt"), encoding="utf-8") as f:
|
||||
self.assertIn("Sitemap: https://example.org/sitemap.xml", f.read())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,291 @@
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import unittest
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from olt import geo # noqa: E402
|
||||
|
||||
NS = "{http://www.topografix.com/GPX/1/1}"
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
M_PER_DEG = math.pi / 180.0 * geo.EARTH_R
|
||||
|
||||
|
||||
def wiggly(n=2000):
|
||||
"""A noisy west-east line near 45N, about 0.0001 degrees per step."""
|
||||
return [[-110.0 + i * 0.0001, 45.0 + 0.00008 * math.sin(i / 7.0)
|
||||
+ 0.00002 * ((i * 7919) % 13 - 6) / 6.0] for i in range(n)]
|
||||
|
||||
|
||||
def offset(lon, lat, east_m, north_m):
|
||||
"""Point east_m/north_m metres from (lon, lat), in degrees."""
|
||||
return [lon + east_m / (M_PER_DEG * math.cos(math.radians(lat))),
|
||||
lat + north_m / M_PER_DEG]
|
||||
|
||||
|
||||
def synthetic_line(lon0, lat0, n=1200, step_m=4.0):
|
||||
"""A straight-ish line east from (lon0, lat0), wiggling by up to ~15 m."""
|
||||
out = []
|
||||
for i in range(n):
|
||||
north = (9.0 * math.sin(i / 13.0) + 4.0 * math.sin(i / 3.1)
|
||||
+ 2.0 * math.sin(i / 0.7))
|
||||
out.append(offset(lon0, lat0, i * step_m, north))
|
||||
return out
|
||||
|
||||
|
||||
def unit(lon, lat):
|
||||
lo, la = math.radians(lon), math.radians(lat)
|
||||
return (math.cos(la) * math.cos(lo), math.cos(la) * math.sin(lo), math.sin(la))
|
||||
|
||||
|
||||
def cross(a, b):
|
||||
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2],
|
||||
a[0] * b[1] - a[1] * b[0])
|
||||
|
||||
|
||||
def dot(a, b):
|
||||
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
|
||||
|
||||
def angle(a, b):
|
||||
return math.atan2(math.sqrt(dot(cross(a, b), cross(a, b))), dot(a, b))
|
||||
|
||||
|
||||
def true_dist_to_segment_m(p, a, b):
|
||||
"""Distance from p to the great-circle arc a-b, independent of any projection.
|
||||
|
||||
Uses 3D unit vectors on the sphere: the perpendicular distance is
|
||||
asin(|p . n|) when the foot lies between a and b, otherwise the nearer end.
|
||||
"""
|
||||
P, A, B = unit(p[0], p[1]), unit(a[0], a[1]), unit(b[0], b[1])
|
||||
n = cross(A, B)
|
||||
nn = math.sqrt(dot(n, n))
|
||||
if nn < 1e-15: # coincident ends: a zero-length segment
|
||||
return min(angle(P, A), angle(P, B)) * geo.EARTH_R
|
||||
n = (n[0] / nn, n[1] / nn, n[2] / nn)
|
||||
s = dot(P, n)
|
||||
q = (P[0] - s * n[0], P[1] - s * n[1], P[2] - s * n[2])
|
||||
qn = math.sqrt(dot(q, q))
|
||||
if qn < 1e-15:
|
||||
return 90.0 * M_PER_DEG
|
||||
q = (q[0] / qn, q[1] / qn, q[2] / qn)
|
||||
if dot(cross(A, q), n) >= -1e-12 and dot(cross(q, B), n) >= -1e-12:
|
||||
return abs(math.asin(max(-1.0, min(1.0, s)))) * geo.EARTH_R
|
||||
return min(angle(P, A), angle(P, B)) * geo.EARTH_R
|
||||
|
||||
|
||||
class SimplifyTest(unittest.TestCase):
|
||||
def assert_dropped_within(self, line, out, limit_m):
|
||||
"""Every dropped point must lie within limit_m of the kept polyline."""
|
||||
positions = []
|
||||
j = 0
|
||||
for i, c in enumerate(line):
|
||||
if j < len(out) and c == out[j]:
|
||||
positions.append(i)
|
||||
j += 1
|
||||
self.assertEqual(j, len(out), "kept points must be a subsequence of the line")
|
||||
self.assertEqual(positions[0], 0)
|
||||
self.assertEqual(positions[-1], len(line) - 1)
|
||||
for k in range(len(positions) - 1):
|
||||
a, b = out[k], out[k + 1]
|
||||
for i in range(positions[k] + 1, positions[k + 1]):
|
||||
d = true_dist_to_segment_m(line[i], a, b)
|
||||
self.assertLessEqual(
|
||||
d, limit_m,
|
||||
f"point {i} is {d:.2f} m from the kept segment "
|
||||
f"({out[k]} -> {out[k + 1]}), limit {limit_m} m")
|
||||
|
||||
def test_keeps_end_points_and_only_drops_interior(self):
|
||||
line = wiggly()
|
||||
out = geo.simplify_part(line, 5.0)
|
||||
self.assertEqual(out[0], line[0])
|
||||
self.assertEqual(out[-1], line[-1])
|
||||
self.assertLess(len(out), len(line))
|
||||
it = iter(line)
|
||||
self.assertTrue(all(any(c == o for c in it) for o in out)) # subsequence
|
||||
|
||||
def test_dropped_points_within_true_tolerance(self):
|
||||
# Checked against spherical ground truth, not the simplification metric.
|
||||
# At these longitudes the old Greenwich-centred projection sheared badly.
|
||||
tol = 5.0
|
||||
for lon0, lat0 in ((-130.0, 63.0), (-70.0, 45.0), (-81.0, 26.0)):
|
||||
with self.subTest(lon=lon0, lat=lat0):
|
||||
line = synthetic_line(lon0, lat0)
|
||||
out = geo.simplify_part(line, tol)
|
||||
self.assertLess(len(out), len(line))
|
||||
self.assert_dropped_within(line, out, tol * 1.05)
|
||||
|
||||
def test_dropped_points_within_true_tolerance_on_real_line(self):
|
||||
parts = geo.read_parts(os.path.join(ROOT, "canol", "line.geojson"))
|
||||
line = max(parts, key=len)
|
||||
out = geo.simplify_part(line, 5.0)
|
||||
self.assertLess(len(out), len(line))
|
||||
self.assert_dropped_within(line, out, 5.0 * 1.05)
|
||||
|
||||
def test_short_and_closed_parts(self):
|
||||
self.assertEqual(geo.simplify_part([[0, 0], [1, 1]], 100), [[0, 0], [1, 1]])
|
||||
loop = [[0, 0], [0, 0.01], [0.01, 0.01], [0.01, 0], [0, 0]]
|
||||
out = geo.simplify_part(loop, 5.0)
|
||||
self.assertEqual(out[0], out[-1])
|
||||
self.assertGreaterEqual(len(out), 4)
|
||||
|
||||
def test_closed_loop_keeps_both_ends(self):
|
||||
# First point equals last: the initial segment is degenerate, so the
|
||||
# algorithm must split on the farthest point and keep both ends.
|
||||
lon0, lat0 = -81.0, 26.0
|
||||
loop = [offset(lon0, lat0, 400.0 * math.cos(2 * math.pi * i / 720),
|
||||
400.0 * math.sin(2 * math.pi * i / 720))
|
||||
for i in range(721)]
|
||||
out = geo.simplify_part(loop, 5.0)
|
||||
self.assertEqual(out[0], loop[0])
|
||||
self.assertEqual(out[-1], loop[-1])
|
||||
self.assertEqual(out[0], out[-1])
|
||||
self.assertLess(len(out), len(loop))
|
||||
self.assert_dropped_within(loop, out, 5.0 * 1.05)
|
||||
|
||||
def test_huge_part_does_not_recurse(self):
|
||||
line = [[-100 + i * 1e-5, 40 + (i % 2) * 1e-6] for i in range(300000)]
|
||||
out = geo.simplify_part(line, 5.0)
|
||||
self.assertEqual((out[0], out[-1]), (line[0], line[-1]))
|
||||
|
||||
def test_long_north_south_part_keeps_true_tolerance(self):
|
||||
# A part spanning ~3 degrees of latitude: a single cosine for the
|
||||
# whole part would be wrong at one end.
|
||||
line = [offset(-130.0, 61.0, 4.0 * math.sin(i / 5.0), i * 400.0)
|
||||
for i in range(900)]
|
||||
out = geo.simplify_part(line, 5.0)
|
||||
self.assertLess(len(out), len(line))
|
||||
self.assert_dropped_within(line, out, 5.0 * 1.05)
|
||||
|
||||
def test_long_north_south_segment_does_not_understate_distance(self):
|
||||
# A 780 km segment with the only deviation near its southern end: the
|
||||
# cosine at the segment's mean latitude would compute 5.5 m as < 5 m
|
||||
# and drop a point that is really too far from the kept line.
|
||||
line = [offset(-130.0, 61.0, 0.0, 0.0),
|
||||
offset(-130.0, 61.001, 5.5, 0.0),
|
||||
offset(-130.0, 68.0, 0.0, 0.0)]
|
||||
out = geo.simplify_part(line, 5.0)
|
||||
self.assertEqual(len(out), 3, "a point 5.5 m off must not be dropped")
|
||||
self.assert_dropped_within(line, out, 5.0 * 1.05)
|
||||
|
||||
def test_elevation_kept(self):
|
||||
out = geo.simplify_part([[0, 0, 5], [0.0005, 0.0005, 6], [0.001, 0.001, 7]], 1.0)
|
||||
self.assertEqual(out, [[0, 0, 5], [0.001, 0.001, 7]])
|
||||
|
||||
|
||||
class MeasureTest(unittest.TestCase):
|
||||
def test_length_one_degree_of_latitude(self):
|
||||
self.assertAlmostEqual(geo.length_km([[[0, 0], [0, 1]]]), 111.195, delta=0.01)
|
||||
|
||||
def test_length_known_pair(self):
|
||||
# one degree of longitude at 60N is half of one at the equator
|
||||
km = geo.length_km([[[10, 60], [11, 60]]])
|
||||
self.assertAlmostEqual(km, 55.6, delta=0.1)
|
||||
|
||||
def test_bbox(self):
|
||||
self.assertEqual(geo.bbox([[[1, 2], [3, 4]], [[-1, 9], [0, 0]]]), [-1, 0, 3, 9])
|
||||
|
||||
def test_round_coords_drops_repeats_keeps_ele(self):
|
||||
out = geo.round_coords([[[1.000001, 2.0, 7], [1.000002, 2.0, 8], [2.0, 3.0, 9]]], 4)
|
||||
self.assertEqual(out, [[[1.0, 2.0, 7], [2.0, 3.0, 9]]])
|
||||
|
||||
def test_round_coords_drops_a_part_that_collapses(self):
|
||||
collapsing = [[-81.503841, 36.648341], [-81.503849, 36.648349]]
|
||||
self.assertEqual(geo.round_coords([collapsing], 4), [])
|
||||
|
||||
def test_round_coords_surviving_part_keeps_its_ends(self):
|
||||
collapsing = [[-81.503841, 36.648341], [-81.503849, 36.648349]]
|
||||
line = [[1.234561, 2.345678], [1.234562, 2.345679], [3.5, 4.5]]
|
||||
out = geo.round_coords([collapsing, line], 4)
|
||||
self.assertEqual(len(out), 1)
|
||||
self.assertEqual(out[0][0], [1.2346, 2.3457])
|
||||
self.assertEqual(out[0][-1], [3.5, 4.5])
|
||||
|
||||
def test_round_coords_all_parts_collapse(self):
|
||||
collapsing = [[-81.503841, 36.648341], [-81.503849, 36.648349]]
|
||||
out = geo.round_coords([collapsing, collapsing], 4)
|
||||
self.assertEqual(out, [])
|
||||
# Callers in geo.py must cope with no parts left.
|
||||
self.assertIsNone(geo.bbox(out))
|
||||
self.assertEqual(geo.join_parts(out), [])
|
||||
root = ET.fromstring(geo.gpx_text(out, "x"))
|
||||
self.assertEqual(root.findall(f".//{NS}trkseg"), [])
|
||||
|
||||
def test_join_parts(self):
|
||||
a = [[0, 0], [0, 0.01]]
|
||||
b = [[0, 0.02], [0, 0.0100005]] # reversed, starts far, ends near a's end
|
||||
out = geo.join_parts([a, b], 100.0)
|
||||
self.assertEqual(len(out), 1)
|
||||
self.assertEqual(len(out[0]), 4)
|
||||
|
||||
|
||||
class JoinPartsTest(unittest.TestCase):
|
||||
@staticmethod
|
||||
def aligned_pair(lat, gap_m, bearing, far_m=300.0):
|
||||
"""Two parts whose near ends are gap_m apart, their far ends harmless.
|
||||
|
||||
The whole assembly is laid out along one bearing, which exercises the
|
||||
bucket grid in every direction (including mostly north-south, where a
|
||||
longitude bucket shrunk by cos(lat) is easy to get wrong).
|
||||
"""
|
||||
east, north = math.sin(bearing), math.cos(bearing)
|
||||
base = [-110.0, lat]
|
||||
near = offset(base[0], base[1], gap_m * east, gap_m * north)
|
||||
a = [offset(base[0], base[1], -far_m * east, -far_m * north), base]
|
||||
b = [near, offset(base[0], base[1], (gap_m + far_m) * east,
|
||||
(gap_m + far_m) * north)]
|
||||
return a, b
|
||||
|
||||
def test_joins_95m_gap_at_all_latitudes(self):
|
||||
rnd = random.Random(20261110)
|
||||
for lat in (30.0, 49.0, 62.0, 65.25, 68.0):
|
||||
for _ in range(200):
|
||||
a, b = self.aligned_pair(lat, 95.0, rnd.uniform(0.0, 2.0 * math.pi))
|
||||
out = geo.join_parts([a, b], 100.0)
|
||||
self.assertEqual(len(out), 1, f"95 m gap not joined at lat {lat}")
|
||||
self.assertEqual(len(out[0]), 4)
|
||||
|
||||
def test_does_not_join_150m_gap(self):
|
||||
rnd = random.Random(7)
|
||||
for lat in (30.0, 49.0, 62.0, 65.25, 68.0):
|
||||
for _ in range(50):
|
||||
a, b = self.aligned_pair(lat, 150.0, rnd.uniform(0.0, 2.0 * math.pi))
|
||||
out = geo.join_parts([a, b], 100.0)
|
||||
self.assertEqual(len(out), 2, f"150 m gap joined at lat {lat}")
|
||||
|
||||
|
||||
class GpxTest(unittest.TestCase):
|
||||
def test_gpx_segments_and_metadata(self):
|
||||
parts = [[[-105.1, 40.1], [-105.2, 40.2]], [[-106.0, 41.0], [-106.1, 41.1], [-106.2, 41.2]]]
|
||||
text = geo.gpx_text(parts, "A & B <Trail>", url="https://example.org/?a=1&b=2",
|
||||
attribution='Me "and" you', licence="ODbL-1.0",
|
||||
licence_text="ODbL 1.0 text")
|
||||
root = ET.fromstring(text)
|
||||
self.assertEqual(root.get("version"), "1.1")
|
||||
trks = root.findall(NS + "trk")
|
||||
self.assertEqual(len(trks), 1)
|
||||
segs = trks[0].findall(NS + "trkseg")
|
||||
self.assertEqual([len(s.findall(NS + "trkpt")) for s in segs], [2, 3])
|
||||
meta = root.find(NS + "metadata")
|
||||
self.assertEqual(meta.find(NS + "name").text, "A & B <Trail>")
|
||||
self.assertEqual(meta.find(NS + "link").get("href"), "https://example.org/?a=1&b=2")
|
||||
self.assertEqual(meta.find(NS + "copyright").get("author"), 'Me "and" you')
|
||||
self.assertIn("ODbL 1.0 text", meta.find(NS + "desc").text)
|
||||
self.assertIsNone(root.find(f".//{NS}ele"))
|
||||
|
||||
def test_gpx_elevation_only_when_present(self):
|
||||
root = ET.fromstring(geo.gpx_text([[[1, 2, 300.5], [1.000001, 2.000001, 301]]], "x"))
|
||||
eles = [e.text for e in root.iter(NS + "ele")]
|
||||
self.assertEqual(eles, ["300.5", "301"])
|
||||
|
||||
def test_no_exponent_in_numbers(self):
|
||||
root = ET.fromstring(geo.gpx_text([[[0.000001, 0.0], [0.5, 0.5]]], "x"))
|
||||
pt = root.find(f".//{NS}trkpt")
|
||||
self.assertEqual(pt.get("lon"), "0.000001")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,431 @@
|
||||
import html.parser
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from olt import md # noqa: E402
|
||||
|
||||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
||||
DOCS = ["README.md", "SOURCES.md", "NOTICE.md",
|
||||
"CONTRIBUTING.md", "CHANGELOG.md", "docs/schema.md"]
|
||||
|
||||
|
||||
def read_doc(name):
|
||||
with open(os.path.join(ROOT, name), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
class TagBalance(html.parser.HTMLParser):
|
||||
VOID = {"hr", "br", "img", "meta", "link", "input", "col"}
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.stack = []
|
||||
self.errors = []
|
||||
self.hrefs = []
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag in self.VOID:
|
||||
return
|
||||
self.stack.append(tag)
|
||||
if tag == "a":
|
||||
self.hrefs.append(dict(attrs).get("href", ""))
|
||||
|
||||
def handle_startendtag(self, tag, attrs):
|
||||
pass
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag in self.VOID:
|
||||
return
|
||||
if self.stack and self.stack[-1] == tag:
|
||||
self.stack.pop()
|
||||
else:
|
||||
self.errors.append("unmatched </%s>, open=%r" % (tag, self.stack))
|
||||
|
||||
|
||||
def check_well_formed(html):
|
||||
checker = TagBalance()
|
||||
checker.feed(html)
|
||||
checker.close()
|
||||
return checker
|
||||
|
||||
|
||||
class TableCounter(html.parser.HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.counts = []
|
||||
self.in_tbody = False
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag == "tbody":
|
||||
self.in_tbody = True
|
||||
self.counts.append(0)
|
||||
elif tag == "tr" and self.in_tbody:
|
||||
self.counts[-1] += 1
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag == "tbody":
|
||||
self.in_tbody = False
|
||||
|
||||
|
||||
class HeadingsTest(unittest.TestCase):
|
||||
def test_levels(self):
|
||||
self.assertEqual(md.render("# One"), '<h1 id="one">One</h1>')
|
||||
self.assertEqual(md.render("### Three"), '<h3 id="three">Three</h3>')
|
||||
self.assertEqual(md.render("###### Six"), '<h6 id="six">Six</h6>')
|
||||
|
||||
def test_offset(self):
|
||||
self.assertEqual(md.render("# One", heading_offset=1),
|
||||
'<h2 id="one">One</h2>')
|
||||
self.assertEqual(md.render("### Three", heading_offset=2),
|
||||
'<h5 id="three">Three</h5>')
|
||||
|
||||
def test_offset_capped_at_h6(self):
|
||||
self.assertTrue(md.render("### Three", heading_offset=9)
|
||||
.startswith("<h6 "))
|
||||
self.assertTrue(md.render("# One", heading_offset=5)
|
||||
.startswith("<h6 "))
|
||||
|
||||
def test_heading_without_space_is_paragraph(self):
|
||||
self.assertEqual(md.render("#nospace"), "<p>#nospace</p>")
|
||||
|
||||
def test_headings_values(self):
|
||||
self.assertEqual(md.headings("# Hello, World!\n\n## B *c*"),
|
||||
[(1, "Hello, World!", "hello-world"),
|
||||
(2, "B c", "b-c")])
|
||||
|
||||
def test_duplicate_slugs_numbered(self):
|
||||
self.assertEqual(
|
||||
[slug for _, _, slug in md.headings("# A\n# A\n# A")],
|
||||
["a", "a-2", "a-3"])
|
||||
|
||||
def test_render_uses_same_slugs_as_headings(self):
|
||||
text = "# Repeat\n\n# Repeat\n"
|
||||
html = md.render(text)
|
||||
for _, _, slug in md.headings(text):
|
||||
self.assertIn('id="%s"' % slug, html)
|
||||
|
||||
def test_heading_inline_markup_excluded_from_slug(self):
|
||||
self.assertEqual(md.headings("## Use `code` here"),
|
||||
[(2, "Use code here", "use-code-here")])
|
||||
|
||||
|
||||
class SectionsTest(unittest.TestCase):
|
||||
def test_basic_split(self):
|
||||
self.assertEqual(
|
||||
md.split_sections("# Title\n\nintro\n\n## One\nbody one\n## Two\nbody two"),
|
||||
[("One", "body one"), ("Two", "body two")])
|
||||
|
||||
def test_preamble_excluded(self):
|
||||
sections = md.split_sections("# Title\n\nintro\n\n## One\nbody\n")
|
||||
self.assertEqual(sections, [("One", "body")])
|
||||
|
||||
def test_subheadings_stay_in_body(self):
|
||||
sections = md.split_sections("## One\ntext\n### Sub\nmore\n## Two\nend\n")
|
||||
self.assertEqual(sections, [("One", "text\n### Sub\nmore"),
|
||||
("Two", "end")])
|
||||
|
||||
def test_default_level_is_two(self):
|
||||
self.assertEqual(len(md.split_sections("# T\n\n# U")), 0)
|
||||
self.assertEqual(len(md.split_sections("# T\n\n## U")), 1)
|
||||
|
||||
def test_bad_level_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
md.split_sections("text", level=0)
|
||||
with self.assertRaises(ValueError):
|
||||
md.split_sections("text", level=7)
|
||||
|
||||
def test_readme_inclusion_rule(self):
|
||||
sections = dict(md.split_sections(read_doc("README.md")))
|
||||
self.assertIn("Inclusion rule", sections)
|
||||
self.assertIn("A long trail here is a named, continuous walking route",
|
||||
sections["Inclusion rule"])
|
||||
self.assertEqual(len(sections), 10)
|
||||
|
||||
|
||||
class ParagraphsTest(unittest.TestCase):
|
||||
def test_simple_paragraph(self):
|
||||
self.assertEqual(md.render("Hello world."), "<p>Hello world.</p>")
|
||||
|
||||
def test_blocks_separated(self):
|
||||
self.assertEqual(md.render("One.\n\nTwo."),
|
||||
"<p>One.</p>\n<p>Two.</p>")
|
||||
|
||||
def test_raw_html_is_escaped(self):
|
||||
html = md.render("Use <id>/trail.toml and <n> trails.")
|
||||
self.assertIn("<id>/trail.toml", html)
|
||||
self.assertIn("<n>", html)
|
||||
self.assertNotIn("<id>", html)
|
||||
|
||||
def test_ampersand_escaped(self):
|
||||
self.assertIn("a & b", md.render("a & b"))
|
||||
|
||||
|
||||
class ListsTest(unittest.TestCase):
|
||||
def test_unordered(self):
|
||||
self.assertEqual(md.render("- a\n- b"),
|
||||
"<ul>\n<li>a</li>\n<li>b</li>\n</ul>")
|
||||
|
||||
def test_ordered(self):
|
||||
self.assertEqual(md.render("1. one\n2. two"),
|
||||
"<ol>\n<li>one</li>\n<li>two</li>\n</ol>")
|
||||
|
||||
def test_ordered_paren_marker(self):
|
||||
self.assertIn("<ol>", md.render("1) one\n2) two"))
|
||||
|
||||
def test_nested(self):
|
||||
html = md.render("- a\n - b\n- c")
|
||||
self.assertIn("<li>a\n<ul>\n<li>b</li>\n</ul></li>", html)
|
||||
|
||||
def test_multiline_item_joined(self):
|
||||
html = md.render("1. first line\n second line\n2. next")
|
||||
self.assertIn("<li>first line\nsecond line</li>", html)
|
||||
|
||||
def test_loose_list_keeps_paragraphs(self):
|
||||
html = md.render("- a\n\n- b")
|
||||
self.assertIn("<li><p>a</p></li>", html)
|
||||
self.assertIn("<li><p>b</p></li>", html)
|
||||
|
||||
def test_markup_inside_items(self):
|
||||
html = md.render("- `code` and **bold**")
|
||||
self.assertIn("<li><code>code</code> and <strong>bold</strong></li>",
|
||||
html)
|
||||
|
||||
|
||||
class TablesTest(unittest.TestCase):
|
||||
def test_header_and_body(self):
|
||||
html = md.render("| a | b |\n| --- | --- |\n| 1 | 2 |")
|
||||
self.assertIn("<thead>", html)
|
||||
self.assertIn("<tbody>", html)
|
||||
self.assertIn('<th scope="col">a</th>', html)
|
||||
self.assertIn("<td>1</td>", html)
|
||||
|
||||
def test_right_align_gets_num_class(self):
|
||||
html = md.render("| a | b |\n| --- | ---: |\n| 1 | 2 |")
|
||||
self.assertIn('<th scope="col" class="num">b</th>', html)
|
||||
self.assertIn('<td class="num">2</td>', html)
|
||||
self.assertIn('<th scope="col">a</th>', html)
|
||||
|
||||
def test_no_inline_styles(self):
|
||||
html = md.render("| a |\n| ---: |\n| 1 |")
|
||||
self.assertNotIn("style=", html)
|
||||
|
||||
def test_needs_alignment_row(self):
|
||||
self.assertNotIn("<table>", md.render("| a | b |\n| 1 | 2 |"))
|
||||
|
||||
def test_links_and_parens_urls_in_cells(self):
|
||||
html = md.render(
|
||||
"| T |\n| --- |\n"
|
||||
"| [source page](https://e.com/POHE_Trail_(Public_NPMap)/0) |")
|
||||
self.assertIn('<a href="https://e.com/POHE_Trail_(Public_NPMap)/0">'
|
||||
"source page</a>", html)
|
||||
|
||||
def test_pipe_in_code_does_not_split(self):
|
||||
html = md.render("| a | b |\n| --- | --- |\n| `x|y` | 2 |")
|
||||
self.assertEqual(html.count("<td>"), 2)
|
||||
self.assertIn("<code>x|y</code>", html)
|
||||
|
||||
def test_escaped_pipe_does_not_split(self):
|
||||
html = md.render("| a |\n| --- |\n| x\\|y |")
|
||||
self.assertEqual(html.count("<td>"), 1)
|
||||
self.assertIn("x|y", html)
|
||||
|
||||
def test_underscores_in_cell_urls_untouched(self):
|
||||
html = md.render("| a |\n| --- |\n"
|
||||
"| [p](https://e.com/a_b_c/0) |")
|
||||
self.assertIn('href="https://e.com/a_b_c/0"', html)
|
||||
|
||||
|
||||
class CodeTest(unittest.TestCase):
|
||||
def test_fenced_with_language(self):
|
||||
html = md.render("```toml\nid = \"x\"\n```")
|
||||
self.assertEqual(html, '<pre><code class="language-toml">'
|
||||
'id = "x"</code></pre>')
|
||||
|
||||
def test_fenced_without_language(self):
|
||||
html = md.render("```\nplain\n```")
|
||||
self.assertEqual(html, "<pre><code>plain</code></pre>")
|
||||
|
||||
def test_fence_content_not_parsed(self):
|
||||
html = md.render("```text\n**no** [link](https://e.com) `x`\n```")
|
||||
self.assertNotIn("<strong>", html)
|
||||
self.assertNotIn("<a ", html)
|
||||
self.assertIn("**no** [link](https://e.com) `x`", html)
|
||||
|
||||
def test_fence_content_escaped(self):
|
||||
self.assertIn("<id>", md.render("```\n<id>\n```"))
|
||||
|
||||
def test_inline_code(self):
|
||||
self.assertEqual(md.render("Use `trail.toml` here."),
|
||||
"<p>Use <code>trail.toml</code> here.</p>")
|
||||
|
||||
def test_code_not_parsed(self):
|
||||
html = md.render("`*not* [em](https://e.com/x_(y))`")
|
||||
self.assertNotIn("<em>", html)
|
||||
self.assertNotIn("<a ", html)
|
||||
|
||||
|
||||
class InlineTest(unittest.TestCase):
|
||||
def test_bold(self):
|
||||
self.assertEqual(md.render("a **bold** b"),
|
||||
"<p>a <strong>bold</strong> b</p>")
|
||||
|
||||
def test_italic(self):
|
||||
self.assertEqual(md.render("a *italic* b"),
|
||||
"<p>a <em>italic</em> b</p>")
|
||||
|
||||
def test_italic_in_bold(self):
|
||||
self.assertEqual(md.render("**a *b* c**"),
|
||||
"<p><strong>a <em>b</em> c</strong></p>")
|
||||
|
||||
def test_unmatched_markers_literal(self):
|
||||
self.assertEqual(md.render("a ** b"), "<p>a ** b</p>")
|
||||
self.assertEqual(md.render("a * b"), "<p>a * b</p>")
|
||||
|
||||
def test_intraword_underscore_literal(self):
|
||||
self.assertIn("agol_flt", md.render("hosts its line as 'agol_flt'"))
|
||||
|
||||
def test_link(self):
|
||||
self.assertEqual(md.render("[text](https://e.com/x)"),
|
||||
'<p><a href="https://e.com/x">text</a></p>')
|
||||
|
||||
def test_link_rewrite(self):
|
||||
html = md.render("[schema](docs/schema.md)",
|
||||
link_rewrite=lambda h: "/data/schema/")
|
||||
self.assertIn('<a href="/data/schema/">schema</a>', html)
|
||||
|
||||
def test_link_rewrite_none_keeps_the_text_only(self):
|
||||
drop = lambda h: None if h.startswith("tools/") else h # noqa: E731
|
||||
html = md.render("See [the tools](tools/build_index.py) and "
|
||||
"[schema](/data/schema/), <https://e.com/a>.",
|
||||
link_rewrite=lambda h: None if h != "/data/schema/" else h)
|
||||
self.assertEqual(html, '<p>See the tools and <a href="/data/schema/">schema</a>, '
|
||||
'https://e.com/a.</p>')
|
||||
html = md.render("| a |\n| --- |\n| [*x* y](tools/x.py) https://e.com/b |",
|
||||
link_rewrite=drop)
|
||||
self.assertIn("<td><em>x</em> y ", html)
|
||||
self.assertIn('<a href="https://e.com/b">https://e.com/b</a>', html)
|
||||
self.assertNotIn("tools/", html)
|
||||
|
||||
def test_link_url_with_parens(self):
|
||||
html = md.render("[p](https://e.com/a_(b)_/c)")
|
||||
self.assertIn('href="https://e.com/a_(b)_/c"', html)
|
||||
|
||||
def test_bare_url(self):
|
||||
html = md.render("see https://www.example.com/x for more")
|
||||
self.assertIn('<a href="https://www.example.com/x">'
|
||||
"https://www.example.com/x</a>", html)
|
||||
|
||||
def test_angle_autolink(self):
|
||||
self.assertIn('<a href="https://e.com/x">https://e.com/x</a>',
|
||||
md.render("<https://e.com/x>"))
|
||||
|
||||
def test_non_link_angle_escaped(self):
|
||||
html = md.render("a <n> b")
|
||||
self.assertIn("<n>", html)
|
||||
self.assertNotIn("<a ", html)
|
||||
|
||||
def test_escape(self):
|
||||
html = md.render("a \\* b \\` c")
|
||||
self.assertIn("a * b ` c", html)
|
||||
self.assertNotIn("<em>", html)
|
||||
|
||||
def test_comment_dropped(self):
|
||||
self.assertEqual(md.render("a <!-- note --> b"), "<p>a b</p>")
|
||||
|
||||
def test_comment_lines_dropped(self):
|
||||
html = md.render("<!-- BEGIN -->\n\ntext\n\n<!-- END -->")
|
||||
self.assertEqual(html, "<p>text</p>")
|
||||
self.assertNotIn("<!--", html)
|
||||
|
||||
def test_comment_inside_fence_kept(self):
|
||||
html = md.render("```\n<!-- keep -->\n```")
|
||||
self.assertIn("<!-- keep -->", html)
|
||||
|
||||
|
||||
class BlocksTest(unittest.TestCase):
|
||||
def test_blockquote(self):
|
||||
html = md.render("> quoted **text**")
|
||||
self.assertEqual(html, "<blockquote>\n<p>quoted "
|
||||
"<strong>text</strong></p>\n</blockquote>")
|
||||
|
||||
def test_multiline_blockquote(self):
|
||||
html = md.render("> one\n> two")
|
||||
self.assertIn("one\ntwo", html)
|
||||
|
||||
def test_hr(self):
|
||||
self.assertEqual(md.render("---"), "<hr>")
|
||||
self.assertEqual(md.render("a\n\n***\n\nb"),
|
||||
"<p>a</p>\n<hr>\n<p>b</p>")
|
||||
|
||||
|
||||
class RealDocumentsTest(unittest.TestCase):
|
||||
def test_all_documents_well_formed(self):
|
||||
for name in DOCS:
|
||||
with self.subTest(doc=name):
|
||||
checker = check_well_formed(md.render(read_doc(name)))
|
||||
self.assertEqual(checker.errors, [])
|
||||
self.assertEqual(checker.stack, [])
|
||||
|
||||
def test_all_link_hrefs_non_empty(self):
|
||||
linked = {"README.md", "SOURCES.md", "NOTICE.md"}
|
||||
for name in DOCS:
|
||||
with self.subTest(doc=name):
|
||||
checker = check_well_formed(md.render(read_doc(name)))
|
||||
if name in linked:
|
||||
self.assertTrue(checker.hrefs,
|
||||
"no links found in %s" % name)
|
||||
for href in checker.hrefs:
|
||||
self.assertTrue(href, "empty href in %s" % name)
|
||||
|
||||
def test_no_comments_survive(self):
|
||||
for name in DOCS:
|
||||
with self.subTest(doc=name):
|
||||
self.assertNotIn("<!--", md.render(read_doc(name)))
|
||||
|
||||
def test_no_inline_styles(self):
|
||||
for name in DOCS:
|
||||
with self.subTest(doc=name):
|
||||
self.assertNotIn("style=", md.render(read_doc(name)))
|
||||
|
||||
def test_readme_table_row_counts(self):
|
||||
counter = TableCounter()
|
||||
counter.feed(md.render(read_doc("README.md")))
|
||||
counter.close()
|
||||
self.assertEqual(counter.counts, [104, 34])
|
||||
|
||||
def test_readme_num_class_present(self):
|
||||
self.assertIn('class="num"', md.render(read_doc("README.md")))
|
||||
|
||||
def test_readme_headings(self):
|
||||
top = md.headings(read_doc("README.md"))[0]
|
||||
self.assertEqual(top, (1, "Open Long Trails", "open-long-trails"))
|
||||
|
||||
def test_readme_offset(self):
|
||||
html = md.render(read_doc("README.md"), heading_offset=1)
|
||||
self.assertNotIn("<h1", html)
|
||||
self.assertIn('<h2 id="open-long-trails">Open Long Trails</h2>', html)
|
||||
|
||||
def test_rewrite_called_for_every_real_link(self):
|
||||
seen = []
|
||||
html = md.render(read_doc("README.md"),
|
||||
link_rewrite=lambda h: seen.append(h) or h)
|
||||
self.assertTrue(seen)
|
||||
for href in seen:
|
||||
self.assertTrue(href)
|
||||
|
||||
def test_rewrite_changes_real_hrefs(self):
|
||||
plain = md.render(read_doc("SOURCES.md"))
|
||||
rewritten = md.render(read_doc("SOURCES.md"),
|
||||
link_rewrite=lambda h: "/go/?u=" + h)
|
||||
self.assertNotEqual(plain, rewritten)
|
||||
self.assertNotIn('href="https://', rewritten)
|
||||
checker = check_well_formed(rewritten)
|
||||
self.assertEqual(checker.errors, [])
|
||||
self.assertEqual(checker.stack, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,451 @@
|
||||
"""Tests for the generated HTML pages (web/olt/pages.py and friends).
|
||||
|
||||
The first run builds the whole site into web/.cache/test-site (about a minute:
|
||||
every line is simplified); later runs are incremental and take seconds.
|
||||
"""
|
||||
import html
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import tomllib
|
||||
import unittest
|
||||
from html.parser import HTMLParser
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
from olt import layout, pages, records, site, trail, words # noqa: E402
|
||||
|
||||
OUT = os.path.join(WEB, ".cache", "test-site")
|
||||
|
||||
# Linked from the shared navigation and footer; written by other page modules.
|
||||
# Remove a path from this set once its page exists.
|
||||
PENDING_PAGES = set()
|
||||
|
||||
|
||||
class Tags(HTMLParser):
|
||||
"""Collect every start tag with its attributes, and <script> contents."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.tags = []
|
||||
self.scripts = []
|
||||
self._in_script = None
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
a = dict(attrs)
|
||||
self.tags.append((tag, a))
|
||||
if tag == "script":
|
||||
self._in_script = [a, ""]
|
||||
|
||||
def handle_data(self, data):
|
||||
if self._in_script is not None:
|
||||
self._in_script[1] += data
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag == "script" and self._in_script is not None:
|
||||
self.scripts.append(tuple(self._in_script))
|
||||
self._in_script = None
|
||||
|
||||
|
||||
def parse(path):
|
||||
p = Tags()
|
||||
with open(path, encoding="utf-8") as f:
|
||||
p.feed(f.read())
|
||||
return p
|
||||
|
||||
|
||||
def html_files(out):
|
||||
for base, _, names in os.walk(out):
|
||||
for n in names:
|
||||
if n.endswith(".html"):
|
||||
yield os.path.join(base, n)
|
||||
|
||||
|
||||
def resolve(out, url):
|
||||
"""File for a root-relative URL, or None when the URL is not a local path."""
|
||||
if not url.startswith("/") or url.startswith("//"):
|
||||
return None
|
||||
path = url.split("#", 1)[0].split("?", 1)[0]
|
||||
if path.endswith("/"):
|
||||
path += "index.html"
|
||||
return os.path.join(out, *path.lstrip("/").split("/"))
|
||||
|
||||
|
||||
class BuiltSiteTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
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)
|
||||
cls.records = records.load_records(ROOT)
|
||||
cls.pages = {}
|
||||
for rec in cls.records:
|
||||
with open(os.path.join(OUT, "trails", rec["id"], "index.html"), encoding="utf-8") as f:
|
||||
cls.pages[rec["id"]] = f.read()
|
||||
|
||||
def test_one_detail_page_per_record(self):
|
||||
found = [d for d in os.listdir(os.path.join(OUT, "trails"))
|
||||
if os.path.isfile(os.path.join(OUT, "trails", d, "index.html"))]
|
||||
self.assertEqual(len(self.records), 138)
|
||||
self.assertEqual(sorted(found), sorted(r["id"] for r in self.records))
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, "index.html")))
|
||||
|
||||
def test_record_files_copied(self):
|
||||
for rec in self.records:
|
||||
tdir = os.path.join(OUT, "trails", rec["id"])
|
||||
self.assertTrue(os.path.isfile(os.path.join(tdir, "trail.toml")), rec["id"])
|
||||
has_release = os.path.isfile(os.path.join(ROOT, rec["id"], "release.txt"))
|
||||
self.assertEqual(os.path.isfile(os.path.join(tdir, "release.txt")), has_release, rec["id"])
|
||||
|
||||
def test_internal_links_resolve(self):
|
||||
missing = set()
|
||||
for path in html_files(OUT):
|
||||
for tag, a in parse(path).tags:
|
||||
for key in ("href", "src"):
|
||||
url = a.get(key)
|
||||
if not url or url.split("?")[0].split("#")[0] in PENDING_PAGES:
|
||||
continue
|
||||
target = resolve(OUT, url)
|
||||
if target and not os.path.isfile(target):
|
||||
missing.add((os.path.relpath(path, OUT), url))
|
||||
self.assertFalse(url.startswith(("http://", "https://")) and tag in ("script", "link")
|
||||
and a.get("rel") != "canonical", f"external asset {url} in {path}")
|
||||
self.assertEqual(sorted(missing)[:20], [])
|
||||
|
||||
def test_no_inline_scripts(self):
|
||||
for path in html_files(OUT):
|
||||
for a, body in parse(path).scripts:
|
||||
if a.get("type") in ("application/json", "application/ld+json"):
|
||||
continue
|
||||
self.assertTrue(a.get("src"), f"inline script in {path}")
|
||||
self.assertEqual(body.strip(), "", f"script with src and a body in {path}")
|
||||
|
||||
def test_style_attributes_only_carry_custom_properties(self):
|
||||
# The CSP allows style="" (style-src-attr) only for data passed to CSS.
|
||||
for path in html_files(OUT):
|
||||
for tag, a in parse(path).tags:
|
||||
if "style" in a:
|
||||
self.assertRegex(a["style"], r"^\s*--[a-z-]+:\s*[-0-9.%]+;?\s*$", f"{tag} in {path}")
|
||||
|
||||
def test_record_only_pages_have_no_line_downloads(self):
|
||||
for rec in self.records:
|
||||
if rec["derived"]["has_line"]:
|
||||
continue
|
||||
for tag, a in parse(os.path.join(OUT, "trails", rec["id"], "index.html")).tags:
|
||||
href = a.get("href", "")
|
||||
line_file = href.startswith("/trails/") and href.endswith((".gpx", ".geojson"))
|
||||
self.assertFalse(line_file or "download" in a, f"{rec['id']} links {href}")
|
||||
|
||||
def test_line_pages_offer_every_download(self):
|
||||
for rec in self.records:
|
||||
if not rec["derived"]["has_line"]:
|
||||
continue
|
||||
page = self.pages[rec["id"]]
|
||||
names = trail_downloads(rec["id"])
|
||||
self.assertTrue(names, rec["id"])
|
||||
for name in names:
|
||||
self.assertIn(f'href="/trails/{rec["id"]}/{name}"', page, rec["id"])
|
||||
self.assertIn("simplified to 5 m", html.unescape(page), rec["id"])
|
||||
|
||||
def test_every_field_appears(self):
|
||||
"""Each field the record carries is on its page (text or number, in some written form)."""
|
||||
for rec in self.records:
|
||||
with open(os.path.join(ROOT, rec["id"], "trail.toml"), "rb") as f:
|
||||
raw = tomllib.load(f)
|
||||
text = page_text(self.pages[rec["id"]])
|
||||
for field, value in leaves(raw):
|
||||
if field.endswith(("line_file", "logo_file")) and value == "":
|
||||
continue # shown as "None included"
|
||||
for form in written_forms(value):
|
||||
if form.lower() in text.lower():
|
||||
break
|
||||
else:
|
||||
self.fail(f"{rec['id']}: {field} = {value!r} not on the page")
|
||||
|
||||
def test_partial_line_notice_and_row_note_for_exactly_the_partial_records(self):
|
||||
"""Decided from the TOML alone: a line, measured, more than 15% from the published length."""
|
||||
expected = set()
|
||||
for rec in self.records:
|
||||
with open(os.path.join(ROOT, rec["id"], "trail.toml"), "rb") as f:
|
||||
raw = tomllib.load(f)
|
||||
v = raw.get("verification", {})
|
||||
if raw["source"].get("line_file") and v.get("verified") and abs(v.get("difference_percent", 0)) > 15:
|
||||
expected.add(rec["id"])
|
||||
self.assertEqual(len(expected), 15)
|
||||
self.assertIn("voyageur", expected)
|
||||
for rec in self.records:
|
||||
page = self.pages[rec["id"]]
|
||||
has_notice = 'class="notice notice--partial"' in page
|
||||
self.assertEqual(has_notice, rec["id"] in expected, rec["id"])
|
||||
if has_notice: # the notice is inside the download panel, above the buttons
|
||||
panel = page[page.index('<section class="panel" id="download"'):]
|
||||
self.assertLess(panel.index("notice--partial"), panel.index('<ul class="downloads">'), rec["id"])
|
||||
v = rec["verification"]
|
||||
text = page_text(panel[:panel.index('<ul class="downloads">')])
|
||||
self.assertIn(f"measures {v['measured_km']:,.1f} km against a published "
|
||||
f"{rec['length_km']:,} km ({words.fmt_percent(v['difference_percent'])})", text)
|
||||
self.assertIn(re.sub(r"\s+", " ", rec["source"]["length_gap_note"]), text, rec["id"])
|
||||
short = rec["id"] in expected and rec["verification"]["difference_percent"] < 0
|
||||
self.assertEqual("In the dataset, partial" in page, short, rec["id"])
|
||||
if rec["derived"]["has_line"]:
|
||||
self.assertRegex(page, r'<dt>Line</dt><dd><a href="#download">In the dataset', rec["id"])
|
||||
rows_seen = set()
|
||||
for path in html_files(OUT):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
rel = os.path.relpath(path, OUT)
|
||||
for m in re.finditer(r'<li class="entry" data-id="([^"]+)"([^>]*)>(.*?)\n</li>', doc, re.S):
|
||||
tid, attrs, row = m.groups()
|
||||
self.assertEqual('data-partial="yes"' in attrs, tid in expected, f"{rel}: {tid}")
|
||||
self.assertEqual(row.count('class="entry__partial"'), 1 if tid in expected else 0, f"{rel}: {tid}")
|
||||
if tid in expected:
|
||||
rows_seen.add(tid)
|
||||
self.assertRegex(page_text(row), r"Line measures [\d,.]+ km (of|against) [\d,]+ km published")
|
||||
entries = len(re.findall(r'<li class="entry" ', doc))
|
||||
partial_rows = len(re.findall(r'<li class="entry" [^>]*data-partial="yes"', doc))
|
||||
self.assertEqual(doc.count('class="entry__partial"'), partial_rows, rel)
|
||||
if not entries:
|
||||
self.assertNotIn("entry__partial", doc, rel)
|
||||
if not rel.startswith("trails" + os.sep):
|
||||
self.assertNotIn("notice--partial", doc, rel)
|
||||
self.assertEqual(rows_seen, expected)
|
||||
|
||||
def test_gpx_first_and_primary_in_every_download_group(self):
|
||||
groups = 0
|
||||
for rec in self.records:
|
||||
for group in re.findall(r'<li class="download">(.*?)</li>', self.pages[rec["id"]], re.S):
|
||||
groups += 1
|
||||
label = html.unescape(re.search(r'<strong id="[^"]+">(.*?)</strong>', group).group(1))
|
||||
links = re.findall(r'<a class="([^"]*)" href="[^"]+\.(gpx|geojson)"[^>]*>(.*?)</a>', group, re.S)
|
||||
kinds = [k for _, k, _ in links]
|
||||
self.assertTrue(kinds, rec["id"])
|
||||
if "gpx" in kinds:
|
||||
self.assertEqual(kinds[0], "gpx", f"{rec['id']}: {label}")
|
||||
self.assertIn("button--primary", links[0][0], rec["id"])
|
||||
self.assertEqual(sorted(kinds, key=lambda k: k != "gpx"), kinds, rec["id"])
|
||||
for cls, kind, inner in links:
|
||||
# the accessible name: the link's text, visually hidden parts included
|
||||
name = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", "", inner))).strip()
|
||||
fmt = "GPX" if kind == "gpx" else "GeoJSON"
|
||||
self.assertRegex(name, rf"^{re.escape(label)}: {fmt}, [\d.,]+ [KM]?B$", rec["id"])
|
||||
self.assertEqual("button--primary" in cls, kind == "gpx", rec["id"])
|
||||
if label.startswith("Extract"):
|
||||
self.assertNotIn("swatch", group, rec["id"])
|
||||
self.assertGreater(groups, 85)
|
||||
|
||||
def test_raw_record_table_holds_every_field(self):
|
||||
for rec in self.records:
|
||||
with open(os.path.join(ROOT, rec["id"], "trail.toml"), "rb") as f:
|
||||
raw = tomllib.load(f)
|
||||
page = self.pages[rec["id"]]
|
||||
self.assertIn('<details class="rawrecord">', page, rec["id"])
|
||||
# the last block of the page's main column
|
||||
tail = page[page.index('<details class="rawrecord">'):]
|
||||
self.assertNotIn('<section class="block"', tail, rec["id"])
|
||||
table = re.search(r'<table class="rawrecord__table">(.*?)</table>', tail, re.S).group(1)
|
||||
rows = {html.unescape(f): re.sub(r"\s+", " ", html.unescape(v)).strip()
|
||||
for f, v in re.findall(r'<tr><th scope="row"><code>(.*?)</code></th><td>(.*?)</td></tr>', table, re.S)}
|
||||
fields = dict(leaves(raw))
|
||||
self.assertEqual(set(rows), set(fields), rec["id"])
|
||||
for field, value in fields.items():
|
||||
self.assertEqual(rows[field], re.sub(r"\s+", " ", trail.raw_value(value)).strip(), f"{rec['id']}: {field}")
|
||||
|
||||
def test_no_raw_tokens_in_the_main_flow(self):
|
||||
for rec in self.records:
|
||||
page = self.pages[rec["id"]]
|
||||
main = page[page.index('<div class="detail__main">'):page.index('<details class="rawrecord">')]
|
||||
codes = set(html.unescape(c) for c in re.findall(r'<code class="raw">(.*?)</code>', main))
|
||||
self.assertLessEqual(codes, {rec["id"]}, rec["id"])
|
||||
# main-column sections are not landmarks; the aside panels are
|
||||
self.assertNotIn('<section class="block" aria-labelledby', page, rec["id"])
|
||||
self.assertIn('<section class="panel" aria-labelledby="links-title">', page, rec["id"])
|
||||
|
||||
def test_record_without_a_line_says_so_once(self):
|
||||
for rec in self.records:
|
||||
page = self.pages[rec["id"]]
|
||||
main = page_text(page[page.index('<div class="detail__main">'):page.index('<details class="rawrecord">')])
|
||||
helper = "Where to ask for the line: a layer or relation page"
|
||||
if rec["derived"]["has_line"]:
|
||||
self.assertEqual(helper in main, bool(rec["source"].get("url")), rec["id"])
|
||||
continue
|
||||
self.assertNotIn(helper, main, rec["id"])
|
||||
for gone in ("none (no line included)", "None (no line included)", "No line to measure", "None recorded"):
|
||||
self.assertNotIn(gone, main, rec["id"])
|
||||
for row in ("Coordinates", "May be passed on", "OpenStreetMap only", "Line source",
|
||||
"Line in this dataset", "Why there is no line"):
|
||||
self.assertNotIn(f"<dt>{row}</dt>", page, rec["id"])
|
||||
if not rec["derived"]["files"].get("shield"):
|
||||
logo = re.search(r'<h2 id="logo-title">Logo</h2>(.*?)</section>', page, re.S).group(1)
|
||||
self.assertEqual(logo.count("<p"), 1, rec["id"])
|
||||
self.assertNotIn("<dl", logo, rec["id"])
|
||||
|
||||
def test_all_guides_button_only_with_more_than_one_guide(self):
|
||||
for rec in self.records:
|
||||
page = self.pages[rec["id"]]
|
||||
if rec["derived"]["has_line"] or rec["derived"]["kind"] != "route":
|
||||
continue
|
||||
frame = page[page.index('<figure class="mapfig mapfig--empty'):page.index("</figure>")]
|
||||
self.assertEqual(">All guides<" in frame, len(rec.get("guide", [])) > 1
|
||||
and rec["route"]["line_policy"] == "open"
|
||||
and any(g.get("access") == "free" for g in rec["guide"]), rec["id"])
|
||||
|
||||
def test_names_marked_with_their_language(self):
|
||||
langs = site.load().name_lang
|
||||
self.assertEqual(langs, {"traversee-charlevoix": "fr", "sentier-national": "fr",
|
||||
"sentier-international-appalaches": "fr"})
|
||||
with open(os.path.join(OUT, "index.html"), encoding="utf-8") as f:
|
||||
home = f.read()
|
||||
by_id = {r["id"]: r for r in self.records}
|
||||
for tid, lang in langs.items():
|
||||
marked = f'<span lang="{lang}">{html.escape(by_id[tid]["name"], quote=True)}</span>'
|
||||
self.assertIn(f'<a href="/trails/{tid}/">{marked}</a>', home, tid)
|
||||
page = self.pages[tid]
|
||||
self.assertIn(f"<h1>{marked}", page, tid)
|
||||
self.assertIn(f'<li aria-current="page">{marked}</li>', page, tid)
|
||||
for path in html_files(OUT):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for m in re.finditer(r'<span lang="([^"]+)">([^<]*)</span>', f.read()):
|
||||
names = {html.escape(by_id[t]["name"], quote=True) for t in langs}
|
||||
self.assertIn(m.group(2), names, path)
|
||||
|
||||
def test_every_table_head_cell_has_col_scope(self):
|
||||
for path in html_files(OUT):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
for head in re.findall(r"<thead>(.*?)</thead>", doc, re.S):
|
||||
for th in re.findall(r"<th\b[^>]*>", head):
|
||||
self.assertIn('scope="col"', th, path)
|
||||
|
||||
def test_app_script_loads_before_maplibre(self):
|
||||
with open(os.path.join(OUT, "index.html"), encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
app, maplibre = doc.index('src="/assets/app.js" defer'), doc.index('maplibre-gl.js" defer')
|
||||
self.assertLess(app, maplibre)
|
||||
|
||||
def test_not_found_page_has_a_search_form(self):
|
||||
with open(os.path.join(OUT, "404.html"), encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
form = re.search(r'<form class="notfound-search" action="/" method="get"[^>]*>(.*?)</form>', doc, re.S)
|
||||
self.assertIsNotNone(form)
|
||||
field = re.search(r'<input class="input" id="([^"]+)" name="q"', form.group(1))
|
||||
self.assertIsNotNone(field)
|
||||
self.assertIn(f'<label class="field__label" for="{field.group(1)}">', form.group(1))
|
||||
self.assertIn('type="submit"', form.group(1))
|
||||
self.assertNotIn("<id>", doc)
|
||||
|
||||
def test_titles_and_descriptions(self):
|
||||
name = site.load().name
|
||||
for path in html_files(OUT):
|
||||
p = parse(path)
|
||||
metas = [a for t, a in p.tags if t == "meta" and a.get("name") == "description"]
|
||||
self.assertEqual(len(metas), 1, path)
|
||||
self.assertTrue(metas[0].get("content"), path)
|
||||
with open(path, encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
self.assertRegex(doc, r"<title>[^<]+</title>", path)
|
||||
self.assertIn(html.escape(name), doc, path)
|
||||
|
||||
|
||||
def trail_downloads(tid):
|
||||
tdir = os.path.join(OUT, "trails", tid)
|
||||
return [n for n in os.listdir(tdir) if n.endswith((".gpx", ".geojson"))]
|
||||
|
||||
|
||||
def page_text(doc):
|
||||
"""Visible text and attribute values of a page, unescaped, with whitespace collapsed."""
|
||||
doc = re.sub(r"<[^>]+?(?:href|title|cite)=\"([^\"]*)\"[^>]*>", lambda m: " " + m.group(1) + " " + m.group(0), doc)
|
||||
text = html.unescape(re.sub(r"<[^>]+>", " ", doc))
|
||||
return re.sub(r"\s+", " ", text)
|
||||
|
||||
|
||||
def leaves(obj, prefix=""):
|
||||
if isinstance(obj, dict):
|
||||
for k, v in obj.items():
|
||||
yield from leaves(v, f"{prefix}.{k}" if prefix else k)
|
||||
elif isinstance(obj, list):
|
||||
for i, v in enumerate(obj):
|
||||
yield from leaves(v, f"{prefix}[{i}]")
|
||||
else:
|
||||
yield prefix, obj
|
||||
|
||||
|
||||
def written_forms(value):
|
||||
"""The ways a value may be written on a page."""
|
||||
if isinstance(value, bool):
|
||||
return [str(value).lower()]
|
||||
if isinstance(value, (int, float)):
|
||||
forms = [str(value), words.fmt_km(value), words.fmt_percent(value), f"{abs(value):.1f}"]
|
||||
return forms
|
||||
text = re.sub(r"\s+", " ", str(value)).strip()
|
||||
return [text, text.replace("`", "")]
|
||||
|
||||
|
||||
class RenderUnitTest(unittest.TestCase):
|
||||
def test_names_are_escaped(self):
|
||||
rec = sample_record(name='Trail & "Quotes" <b>bold</b>')
|
||||
_, description, body, _ = trail.render(rec, site.Site("Site & Co", "Tag"))
|
||||
doc = layout.layout(rec["name"], body, path="/trails/x/", description=description,
|
||||
site=site.Site("Site & Co", "Tag"))
|
||||
self.assertIn("Trail & "Quotes" <b>bold</b>", doc)
|
||||
self.assertNotIn("<b>bold</b>", doc)
|
||||
self.assertNotIn("<script>alert", doc)
|
||||
self.assertIn("Site & Co", doc)
|
||||
self.assertIn('href="https://example.org/?a=1&b=2"', doc)
|
||||
|
||||
def test_canonical_only_with_base_url(self):
|
||||
doc = layout.layout("T", "", path="/trails/x/", site=site.Site("N", "T"))
|
||||
self.assertNotIn('rel="canonical"', doc)
|
||||
doc = layout.layout("T", "", path="/trails/x/", site=site.Site("N", "T", base_url="https://example.org/"))
|
||||
self.assertIn('<link rel="canonical" href="https://example.org/trails/x/">', doc)
|
||||
|
||||
def test_site_name_comes_from_settings(self):
|
||||
doc = layout.layout("", "", path="/", site=site.Site("Another Name", "A tagline"))
|
||||
self.assertIn("<title>Another Name: A tagline</title>", doc)
|
||||
self.assertNotIn("Long Hikes", doc)
|
||||
|
||||
def test_report_links_need_repo_url(self):
|
||||
self.assertNotIn("/issues", layout.footer(site.Site("N", "T")))
|
||||
self.assertIn("https://example.org/repo/issues", layout.footer(site.Site("N", "T", repo_url="https://example.org/repo")))
|
||||
|
||||
def test_render_site_on_a_synthetic_record(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo, out = os.path.join(tmp, "repo"), os.path.join(tmp, "out")
|
||||
os.makedirs(os.path.join(repo, "x"))
|
||||
with open(os.path.join(repo, "x", "trail.toml"), "w", encoding="utf-8") as f:
|
||||
f.write('id = "x"\n')
|
||||
rec = sample_record(name="A & B")
|
||||
n = pages.render_site([rec], out, repo, site=site.Site("N", "T"))
|
||||
# trail page + home + 404 + regions index + 1 region + routes,
|
||||
# sources, logos, about, data, schema, changelog
|
||||
self.assertEqual(n, 12)
|
||||
with open(os.path.join(out, "trails", "x", "index.html"), encoding="utf-8") as f:
|
||||
self.assertIn("A & B", f.read())
|
||||
with open(os.path.join(out, "index.html"), encoding="utf-8") as f:
|
||||
self.assertIn('href="/trails/x/"', f.read())
|
||||
|
||||
|
||||
def sample_record(name):
|
||||
return {
|
||||
"id": "x", "name": name, "short_name": "X", "country": "US", "regions": ["AZ"],
|
||||
"length_km": 100, "length_note": "about 62 mi", "tier": "regional", "designation": "A & B Association",
|
||||
"wave": 1,
|
||||
"source": {"status": "none", "publisher": "P", "url": "https://example.org/?a=1&b=2", "format": "None",
|
||||
"crs": "EPSG:4326", "licence": "none-stated", "licence_text": "None.", "attribution": "none",
|
||||
"osm_only": False, "mainline": "None", "source_checked": "2026-11-10", "redistributable": True,
|
||||
"line_source": "none (no line included)", "line_file": "",
|
||||
"line_absent_reason": "No line is included. <script>alert(1)</script>"},
|
||||
"osm": {"relation": 0, "note": "None"},
|
||||
"shield": {"status": "no-logo-exists", "logo_source": "", "contact": "P", "note": "None",
|
||||
"logo_file": "", "logo_owner": "P"},
|
||||
"verification": {"verified": False, "note": "No line to measure."},
|
||||
"derived": {"kind": "designated", "has_line": False, "length_mi": 62, "files": {},
|
||||
"status": "record-only", "downloads": []},
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from olt import records # noqa: E402
|
||||
|
||||
|
||||
class RecordsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.recs = records.load_records()
|
||||
|
||||
def test_counts(self):
|
||||
self.assertEqual(len(self.recs), 138)
|
||||
self.assertEqual(sum(r["derived"]["kind"] == "route" for r in self.recs), 34)
|
||||
self.assertEqual(sum(r["derived"]["kind"] == "designated" for r in self.recs), 104)
|
||||
self.assertEqual(sum(r["derived"]["has_line"] for r in self.recs), 85)
|
||||
|
||||
def test_sorted_by_id(self):
|
||||
ids = [r["id"] for r in self.recs]
|
||||
self.assertEqual(ids, sorted(ids))
|
||||
|
||||
def test_derived_fields(self):
|
||||
by_id = {r["id"]: r for r in self.recs}
|
||||
ct = by_id["colorado-trail"]
|
||||
self.assertEqual(ct["derived"]["status"], "included")
|
||||
self.assertEqual(ct["derived"]["length_mi"], 486)
|
||||
self.assertEqual(sorted(ct["derived"]["files"]["extracts"]), ["osm", "usfs"])
|
||||
self.assertEqual(ct["derived"]["files"]["line"], "colorado-trail/line.geojson")
|
||||
self.assertEqual(ct["name"], "Colorado Trail") # TOML fields unchanged
|
||||
|
||||
def test_status_matches_csv(self):
|
||||
import csv
|
||||
path = os.path.join(records.ROOT, "trails.csv")
|
||||
with open(path, encoding="utf-8", newline="") as f:
|
||||
status = {row["id"]: row["status"] for row in csv.DictReader(f)}
|
||||
for r in self.recs:
|
||||
self.assertEqual(r["derived"]["status"], status[r["id"]])
|
||||
|
||||
def test_line_file_exists_when_has_line(self):
|
||||
for r in self.recs:
|
||||
self.assertEqual(r["derived"]["has_line"], "line" in r["derived"]["files"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Logo thumbnails: the committed web/thumbs, what the built pages show, and the fallback."""
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from html.parser import HTMLParser
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
from olt import records, thumbs # noqa: E402
|
||||
|
||||
OUT = os.path.join(WEB, ".cache", "test-site")
|
||||
MAX_SIDE = 256
|
||||
|
||||
|
||||
class Imgs(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.imgs = []
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag == "img":
|
||||
self.imgs.append(dict(attrs))
|
||||
|
||||
|
||||
def page_imgs(path):
|
||||
p = Imgs()
|
||||
with open(path, encoding="utf-8") as f:
|
||||
p.feed(f.read())
|
||||
return p.imgs
|
||||
|
||||
|
||||
def html_files(out):
|
||||
for base, _, names in os.walk(out):
|
||||
for n in names:
|
||||
if n.endswith(".html"):
|
||||
yield os.path.join(base, n)
|
||||
|
||||
|
||||
def repository_png_logos():
|
||||
"""{id: path} for each <id>/shield.png directly under the repository root."""
|
||||
found = {}
|
||||
for name in os.listdir(ROOT):
|
||||
path = os.path.join(ROOT, name, "shield.png")
|
||||
if not name.startswith((".", "_")) and os.path.isfile(path):
|
||||
found[name] = path
|
||||
return found
|
||||
|
||||
|
||||
def build():
|
||||
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
|
||||
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
class ThumbFilesTest(unittest.TestCase):
|
||||
def test_every_repository_png_logo_has_a_thumbnail_no_larger_than_256(self):
|
||||
logos = repository_png_logos()
|
||||
self.assertTrue(logos)
|
||||
for tid in logos:
|
||||
thumb = os.path.join(WEB, "thumbs", f"{tid}.png")
|
||||
self.assertTrue(os.path.isfile(thumb), f"{tid}: no {thumb}")
|
||||
w, h = thumbs.png_size(thumb)
|
||||
self.assertLessEqual(w, MAX_SIDE, tid)
|
||||
self.assertLessEqual(h, MAX_SIDE, tid)
|
||||
self.assertGreater(min(w, h), 0, tid)
|
||||
|
||||
def test_no_thumbnail_without_a_source(self):
|
||||
logos = repository_png_logos()
|
||||
thumbs_dir = os.path.join(WEB, "thumbs")
|
||||
for name in os.listdir(thumbs_dir):
|
||||
self.assertIn(name[:-len(".png")], logos, f"orphan thumbnail {name}")
|
||||
|
||||
def test_fallback_to_full_size_when_no_thumbnail(self):
|
||||
tid = "x"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo, out, empty = (os.path.join(tmp, n) for n in ("repo", "out", "thumbs"))
|
||||
os.makedirs(os.path.join(repo, tid))
|
||||
os.makedirs(empty)
|
||||
src = repository_png_logos()["cohos"]
|
||||
shutil.copyfile(src, os.path.join(repo, tid, "shield.png"))
|
||||
os.makedirs(os.path.join(out, "trails", tid))
|
||||
rec = {"id": tid, "derived": {"files": {"shield": f"{tid}/shield.png"}}}
|
||||
err = io.StringIO()
|
||||
with contextlib.redirect_stderr(err):
|
||||
thumbs.prepare(rec, out, repo, thumb_dir=empty)
|
||||
self.assertIn(f"{tid}:", err.getvalue())
|
||||
self.assertEqual(err.getvalue().count("warning"), 1)
|
||||
logo = rec["derived"]["logo_img"]
|
||||
self.assertEqual(logo["src"], f"/trails/{tid}/shield.png")
|
||||
self.assertEqual((logo["width"], logo["height"]), thumbs.png_size(src))
|
||||
self.assertFalse(os.path.exists(os.path.join(out, "trails", tid, thumbs.THUMB_NAME)))
|
||||
|
||||
def test_svg_logo_gets_no_thumbnail(self):
|
||||
rec = {"id": "x", "derived": {"files": {"shield": "x/shield.svg"}, "logo_img": {"src": "stale"}}}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
thumbs.prepare(rec, tmp, tmp, thumb_dir=tmp)
|
||||
self.assertNotIn("logo_img", rec["derived"])
|
||||
|
||||
|
||||
class BuiltPagesTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
os.makedirs(os.path.dirname(OUT), exist_ok=True)
|
||||
build()
|
||||
cls.records = records.load_records(ROOT)
|
||||
cls.png = [r["id"] for r in cls.records
|
||||
if r["derived"]["files"].get("shield", "").endswith(".png")]
|
||||
cls.all_imgs = [(path, img) for path in html_files(OUT) for img in page_imgs(path)]
|
||||
|
||||
def test_list_pages_show_thumbnails_not_full_size_pngs(self):
|
||||
for path, img in self.all_imgs:
|
||||
self.assertFalse(img.get("src", "").endswith("/shield.png"), f"{path} shows {img.get('src')}")
|
||||
for page in ("index.html", os.path.join("logos", "index.html")):
|
||||
with open(os.path.join(OUT, page), encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
for tid in self.png:
|
||||
self.assertIn(f'src="/trails/{tid}/shield-thumb.png"', doc, f"{page} for {tid}")
|
||||
|
||||
def test_thumbnail_width_and_height_match_the_file(self):
|
||||
seen = 0
|
||||
for path, img in self.all_imgs:
|
||||
src = img.get("src", "")
|
||||
if not src.endswith("/" + thumbs.THUMB_NAME):
|
||||
continue
|
||||
seen += 1
|
||||
w, h = thumbs.png_size(os.path.join(OUT, src.lstrip("/")))
|
||||
self.assertEqual((img.get("width"), img.get("height")), (str(w), str(h)), path)
|
||||
self.assertEqual(img.get("decoding"), "async", path)
|
||||
self.assertGreaterEqual(seen, len(self.png) * 2)
|
||||
|
||||
def test_record_header_logo_is_eager_and_links_full_size(self):
|
||||
for tid in self.png:
|
||||
with open(os.path.join(OUT, "trails", tid, "index.html"), encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
self.assertIn(f'<a href="/trails/{tid}/shield.png"><img src="/trails/{tid}/shield-thumb.png"', doc, tid)
|
||||
header = [i for i in page_imgs(os.path.join(OUT, "trails", tid, "index.html"))
|
||||
if i.get("src") == f"/trails/{tid}/shield-thumb.png"]
|
||||
self.assertEqual(len(header), 1, tid)
|
||||
self.assertNotIn("loading", header[0], tid)
|
||||
|
||||
def test_logos_page_links_full_size_and_is_lazy(self):
|
||||
for tid in self.png:
|
||||
with open(os.path.join(OUT, "logos", "index.html"), encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
self.assertIn(f'<a href="/trails/{tid}/shield.png"><img src="/trails/{tid}/shield-thumb.png"', doc, tid)
|
||||
for img in page_imgs(os.path.join(OUT, "logos", "index.html")):
|
||||
if img.get("src", "").endswith(thumbs.THUMB_NAME):
|
||||
self.assertEqual(img.get("loading"), "lazy")
|
||||
|
||||
def test_thumbnails_survive_a_second_build(self):
|
||||
build()
|
||||
for tid in self.png:
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, "trails", tid, thumbs.THUMB_NAME)), tid)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
After Width: | Height: | Size: 6.6 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 7.2 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 6.6 KiB |
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Make the small PNG logo thumbnails the site shows in lists.
|
||||
|
||||
For every <id>/shield.png in the repository root, writes web/thumbs/<id>.png,
|
||||
scaled to fit within 256 x 256 px (never enlarged), metadata stripped and
|
||||
transparency kept. Needs ImageMagick 7 (`magick`) on the PATH; runs optipng
|
||||
too when it is installed. Run on a developer machine and commit the output:
|
||||
the site build itself is standard library only and does not run this.
|
||||
|
||||
python3 web/tools/make_thumbs.py [--force]
|
||||
|
||||
A thumbnail newer than its source is left alone unless --force is given.
|
||||
Thumbnails whose source no longer exists are removed.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
THUMBS = os.path.join(os.path.dirname(HERE), "thumbs")
|
||||
MAX_SIDE = 256
|
||||
|
||||
|
||||
def sources():
|
||||
"""{id: path} for each <id>/shield.png directly under the repository root."""
|
||||
found = {}
|
||||
for name in sorted(os.listdir(ROOT)):
|
||||
path = os.path.join(ROOT, name, "shield.png")
|
||||
if not name.startswith((".", "_")) and os.path.isfile(path):
|
||||
found[name] = path
|
||||
return found
|
||||
|
||||
|
||||
def make_thumb(src, dst):
|
||||
"""Write one thumbnail with ImageMagick, then optimise it when optipng is present."""
|
||||
cmd = ["magick", src, "-strip", "-resize", f"{MAX_SIDE}x{MAX_SIDE}>",
|
||||
"PNG32:" + dst]
|
||||
try:
|
||||
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
except subprocess.CalledProcessError as e:
|
||||
if os.path.exists(dst):
|
||||
os.remove(dst)
|
||||
sys.exit(f"make_thumbs: magick failed on {os.path.relpath(src, ROOT)}: "
|
||||
f"{e.stderr.decode(errors='replace').strip()}")
|
||||
if shutil.which("optipng"):
|
||||
subprocess.run(["optipng", "-quiet", "-o2", dst], check=True)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description="Make web/thumbs/<id>.png from each <id>/shield.png.")
|
||||
ap.add_argument("--force", action="store_true", help="rebuild thumbnails that are up to date")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if shutil.which("magick") is None:
|
||||
sys.exit("make_thumbs: 'magick' (ImageMagick 7) was not found on the PATH; install ImageMagick and retry")
|
||||
|
||||
os.makedirs(THUMBS, exist_ok=True)
|
||||
srcs = sources()
|
||||
written = skipped = removed = 0
|
||||
total = 0
|
||||
for tid, src in srcs.items():
|
||||
dst = os.path.join(THUMBS, f"{tid}.png")
|
||||
if not args.force and os.path.isfile(dst) and os.path.getmtime(dst) >= os.path.getmtime(src):
|
||||
skipped += 1
|
||||
continue
|
||||
make_thumb(src, dst)
|
||||
size = os.path.getsize(dst)
|
||||
total += size
|
||||
written += 1
|
||||
print(f"wrote {os.path.relpath(dst, ROOT)} ({size} bytes)")
|
||||
|
||||
for name in sorted(os.listdir(THUMBS)):
|
||||
if name.endswith(".png") and name[:-4] not in srcs:
|
||||
os.remove(os.path.join(THUMBS, name))
|
||||
removed += 1
|
||||
print(f"removed {os.path.relpath(os.path.join(THUMBS, name), ROOT)} (no source)")
|
||||
|
||||
print(f"total: {written} written ({total} bytes), {skipped} up to date, {removed} removed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||