Sort every list of trails, and map trails that have no track
Sorting. Every list of trails has a "Sort by" menu: name, length, time or climb, each in both directions. Where the list is a table, the Trail, Length, Time and Climb heads sort on click and reverse on a second click. Lists open by name, A to Z, except the four that are defined by an order (the longest, under 100 km, a week or less, one to two weeks). The chosen order is kept in the page address. The pages are written in their default order, so they are right without JavaScript. Maps. A trail with no track but a known start and end is drawn as a dotted straight line between the two with a ring at each; one with a single known point is drawn as a ring. They follow the filters, the row highlight and the popup like any track, and that trail's own page shows a map in place of the empty frame. The legend, the caption and the popup say the dotted line is not the trail's path. It gives no download, no GPX status and no elevation. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
d84116ce3a
commit
51baaa401e
15 files changed
+1049
-149
No files matched your search
+272
-60
@@ -95,17 +95,28 @@
|
||||
return g.type === 'MultiLineString' ? g.coordinates : [];
|
||||
}
|
||||
|
||||
function pointsOf(feature) {
|
||||
var g = feature.geometry || {};
|
||||
if (g.type === 'Point') return [g.coordinates];
|
||||
return g.type === 'MultiPoint' ? g.coordinates : [];
|
||||
}
|
||||
|
||||
function allCoords(feature) {
|
||||
var out = [];
|
||||
linesOf(feature).forEach(function (line) { line.forEach(function (p) { out.push(p); }); });
|
||||
pointsOf(feature).forEach(function (p) { out.push(p); });
|
||||
return out;
|
||||
}
|
||||
|
||||
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];
|
||||
});
|
||||
allCoords(f).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;
|
||||
@@ -114,18 +125,24 @@
|
||||
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];
|
||||
});
|
||||
allCoords(feature).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;
|
||||
}
|
||||
|
||||
/* A single sketch point has no span; give it about a county of ground. */
|
||||
function ensureSpan(bbox) {
|
||||
var b = bbox.slice();
|
||||
if (b[2] - b[0] < 0.02) { var cx = (b[0] + b[2]) / 2; b[0] = cx - 0.25; b[2] = cx + 0.25; }
|
||||
if (b[3] - b[1] < 0.02) { var cy = (b[1] + b[3]) / 2; b[1] = cy - 0.18; b[3] = cy + 0.18; }
|
||||
return b;
|
||||
}
|
||||
|
||||
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; }
|
||||
|
||||
@@ -139,6 +156,7 @@
|
||||
|
||||
/* Lines on a plain graticule (Web Mercator), no tiles. Returns the drawn extent. */
|
||||
function drawFallback(host, fc, bbox, routeMain) {
|
||||
bbox = ensureSpan(bbox);
|
||||
var rect = host.getBoundingClientRect();
|
||||
var W = Math.max(Math.round(rect.width), 280);
|
||||
var H = Math.max(Math.round(rect.height), 180);
|
||||
@@ -179,12 +197,27 @@
|
||||
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); });
|
||||
var isRoute = p.kind === 'route' || (routeMain && (p.role === 'main' || p.sketch));
|
||||
var mod = p.sketch ? ' fallback__line--sketch' + (isRoute ? ' fallback__line--sketch-route' : '')
|
||||
: p.role === 'alternate' ? ' fallback__line--alternate'
|
||||
: isRoute ? ' fallback__line--route' : '';
|
||||
return { d: d, mod: mod, id: p.id || '', sketch: !!p.sketch };
|
||||
}).filter(function (l) { return l.d; });
|
||||
drawn.filter(function (l) { return !l.sketch; }).forEach(function (l) { path('fallback__casing', l.d, l.id); });
|
||||
drawn.forEach(function (l) { path('fallback__line' + l.mod, l.d, l.id); });
|
||||
fc.features.forEach(function (f) {
|
||||
var p = f.properties || {};
|
||||
var ringCls = 'fallback__ring' + ((p.kind === 'route' || routeMain) ? ' fallback__ring--route' : '');
|
||||
pointsOf(f).forEach(function (pt) {
|
||||
var c = document.createElementNS(ns, 'circle');
|
||||
c.setAttribute('class', ringCls);
|
||||
c.setAttribute('cx', x(pt[0]).toFixed(1));
|
||||
c.setAttribute('cy', y(pt[1]).toFixed(1));
|
||||
c.setAttribute('r', '4');
|
||||
if (p.id) c.setAttribute('data-id', p.id);
|
||||
svg.appendChild(c);
|
||||
});
|
||||
});
|
||||
host.replaceChildren(svg);
|
||||
return ext;
|
||||
}
|
||||
@@ -258,13 +291,29 @@
|
||||
});
|
||||
}
|
||||
|
||||
/* Track features carry no sketch property at all, so has/!has is the
|
||||
type-safe test (a != against true would compare boolean with null). */
|
||||
var NOT_SKETCH = ['!', ['has', 'sketch']];
|
||||
var IS_SKETCH = ['has', 'sketch'];
|
||||
|
||||
function layerDefs(kind, routeMain) {
|
||||
if (kind === 'overview') {
|
||||
return [
|
||||
{ id: 'olt-casing', color: '--casing', width: [3, 4, 9, 9] },
|
||||
{ id: 'olt-casing', color: '--casing', width: [3, 4, 9, 9], filter: NOT_SKETCH },
|
||||
{ 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 }
|
||||
{ id: 'olt-hi-point', type: 'circle', stroke: '--ink', strokeWidth: 3, radius: [3, 5, 9, 9], filter: ['==', ['get', 'id'], ''] },
|
||||
{ id: 'olt-line', color: '--trail', width: [3, 1.6, 9, 4], filter: ['all', NOT_SKETCH, ['!=', ['get', 'kind'], 'route']], hit: true },
|
||||
{ id: 'olt-route', color: '--route', width: [3, 1.6, 9, 4], dash: [1.6, 1.1], filter: ['all', NOT_SKETCH, ['==', ['get', 'kind'], 'route']], hit: true },
|
||||
{ id: 'olt-sketch', color: '--trail', width: [3, 2, 9, 3.5], dash: [0, 2], cap: 'round', filter: ['all', IS_SKETCH, ['!=', ['get', 'kind'], 'route']], hit: true },
|
||||
{ id: 'olt-sketch-route', color: '--route', width: [3, 2, 9, 3.5], dash: [0, 2], cap: 'round', filter: ['all', IS_SKETCH, ['==', ['get', 'kind'], 'route']], hit: true },
|
||||
{ id: 'olt-sketch-points', type: 'circle', strokeByKind: true, strokeWidth: 2, radius: [3, 3, 9, 6], filter: IS_SKETCH, hit: true }
|
||||
];
|
||||
}
|
||||
if (kind === 'sketch') {
|
||||
var col = routeMain ? '--route' : '--trail';
|
||||
return [
|
||||
{ id: 'olt-sketch', color: col, width: [5, 3, 12, 5], dash: [0, 2], cap: 'round', filter: IS_SKETCH },
|
||||
{ id: 'olt-sketch-points', type: 'circle', stroke: col, strokeWidth: 2.5, radius: [5, 5, 12, 8], filter: IS_SKETCH }
|
||||
];
|
||||
}
|
||||
return [
|
||||
@@ -275,22 +324,40 @@
|
||||
];
|
||||
}
|
||||
|
||||
function circleStroke(def) {
|
||||
if (def.strokeByKind) return ['match', ['get', 'kind'], 'route', token('--route'), token('--trail')];
|
||||
return token(def.stroke || '--trail');
|
||||
}
|
||||
|
||||
/* 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;
|
||||
var layer;
|
||||
if (def.type === 'circle') {
|
||||
layer = {
|
||||
id: def.id, type: 'circle', source: 'olt',
|
||||
paint: {
|
||||
'circle-radius': ['interpolate', ['linear'], ['zoom'], def.radius[0], def.radius[1], def.radius[2], def.radius[3]],
|
||||
'circle-color': token('--casing'),
|
||||
'circle-stroke-color': circleStroke(def),
|
||||
'circle-stroke-width': def.strokeWidth || 2
|
||||
}
|
||||
};
|
||||
} else {
|
||||
layer = {
|
||||
id: def.id,
|
||||
type: 'line',
|
||||
source: 'olt',
|
||||
layout: { 'line-join': 'round', 'line-cap': def.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);
|
||||
});
|
||||
@@ -318,8 +385,10 @@
|
||||
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');
|
||||
/* A wide map of Alaska reaches past 180°: name that longitude as the east one it is. */
|
||||
var wrap = function (lon) { return ((lon + 540) % 360) - 180; };
|
||||
if (nw) nw.textContent = dms(ext.n, 'N', 'S') + ' ' + dms(wrap(ext.w), 'E', 'W');
|
||||
if (se) se.textContent = dms(ext.s, 'N', 'S') + ' ' + dms(wrap(ext.e), 'E', 'W');
|
||||
}
|
||||
function redrawFallback() {
|
||||
if (!entry.ready && entry.fc) {
|
||||
@@ -330,10 +399,11 @@
|
||||
function fail(reason) {
|
||||
if (entry.ready) return;
|
||||
host.dataset.state = 'fallback';
|
||||
status.textContent = 'Base map unavailable (' + reason + '). The track is drawn on a plain graticule.';
|
||||
status.textContent = 'Base map unavailable (' + reason + '). ' +
|
||||
(kind === 'sketch' ? 'The start and end are drawn on a plain graticule.' : 'The track is drawn on a plain graticule.');
|
||||
}
|
||||
|
||||
status.textContent = 'Loading the track…';
|
||||
status.textContent = kind === 'sketch' ? 'Loading the map…' : 'Loading the track…';
|
||||
var dataReady = fetch(fig.dataset.src, { credentials: 'same-origin' })
|
||||
.then(function (r) {
|
||||
if (!r.ok) throw new Error(r.status);
|
||||
@@ -348,7 +418,11 @@
|
||||
fc.features.forEach(function (f) {
|
||||
var id = (f.properties || {}).id;
|
||||
var fb = id && bboxOfFeature(f);
|
||||
if (fb) entry.boundsById[id] = fb;
|
||||
if (!fb) return;
|
||||
var prev = entry.boundsById[id];
|
||||
entry.boundsById[id] = prev
|
||||
? [Math.min(prev[0], fb[0]), Math.min(prev[1], fb[1]), Math.max(prev[2], fb[2]), Math.max(prev[3], fb[3])]
|
||||
: fb;
|
||||
});
|
||||
}
|
||||
if (!entry.ready && entry.mapStarted && window.maplibregl) status.textContent = 'Loading the base map…';
|
||||
@@ -444,7 +518,14 @@
|
||||
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)); });
|
||||
defs.forEach(function (def) {
|
||||
if (def.type === 'circle') {
|
||||
map.setPaintProperty(def.id, 'circle-color', token('--casing'));
|
||||
map.setPaintProperty(def.id, 'circle-stroke-color', circleStroke(def));
|
||||
} else {
|
||||
map.setPaintProperty(def.id, 'line-color', token(def.color));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -465,7 +546,9 @@
|
||||
|
||||
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 || '']);
|
||||
if (!m.map || !m.ready) return;
|
||||
if (m.map.getLayer('olt-hi')) m.map.setFilter('olt-hi', ['==', ['get', 'id'], id || '']);
|
||||
if (m.map.getLayer('olt-hi-point')) m.map.setFilter('olt-hi-point', ['==', ['get', 'id'], id || '']);
|
||||
});
|
||||
document.querySelectorAll('.entry.is-highlit').forEach(function (li) { li.classList.remove('is-highlit'); });
|
||||
if (id) {
|
||||
@@ -495,6 +578,15 @@
|
||||
meta.textContent = lengthText(Number(p.length_km)) + (p.kind === 'route' ? ' · Route' : '');
|
||||
box.appendChild(a);
|
||||
box.appendChild(meta);
|
||||
if (p.sketch) {
|
||||
var g = e.features[0].geometry || {};
|
||||
var pointOnly = (g.type === 'MultiPoint' && g.coordinates.length === 1) || g.type === 'Point';
|
||||
var note = document.createElement('p');
|
||||
note.textContent = pointOnly
|
||||
? 'No GPX here. The ring only marks one end of it; it is not the trail\u2019s path.'
|
||||
: 'No GPX here. The dotted line only joins the start and the end; it is not the trail\u2019s path.';
|
||||
box.appendChild(note);
|
||||
}
|
||||
popup.setLngLat(e.lngLat).setDOMContent(box).addTo(map);
|
||||
});
|
||||
});
|
||||
@@ -542,7 +634,7 @@
|
||||
if (!map || !entry.ready) return;
|
||||
var inSet = ['in', ['get', 'id'], ['literal', ids]];
|
||||
entry.defs.forEach(function (def) {
|
||||
if (def.id === 'olt-hi') return;
|
||||
if (def.id.indexOf('olt-hi') === 0) return;
|
||||
map.setFilter(def.id, def.filter ? ['all', def.filter, inSet] : inSet);
|
||||
});
|
||||
fitToVisible(entry, ids);
|
||||
@@ -556,6 +648,133 @@
|
||||
if (window.maplibregl || document.readyState === 'complete') startMaps();
|
||||
else window.addEventListener('load', startMaps);
|
||||
|
||||
/* 2b. Sorting every list of trails -----------------------------------------
|
||||
The same orders as facets.SORTS in Python, over the rows' data-*
|
||||
attributes. The "Sort by" select is the one control for keyboard and
|
||||
screen-reader users (the column-head buttons are aria-hidden pointer
|
||||
shortcuts that always agree with it); each new order is announced in
|
||||
the [data-sort-status] live region. ?sort=<key> is written with
|
||||
replaceState when the order is not the page's default, and honoured
|
||||
on load and on back/forward. */
|
||||
|
||||
var SORT_KEYS = { 'name': 1, 'name-desc': 1, 'length-desc': 1, 'length-asc': 1,
|
||||
'time-asc': 1, 'time-desc': 1, 'climb-desc': 1, 'climb-asc': 1 };
|
||||
var SORT_OLD = { 'long': 'length-desc', 'short': 'length-asc', 'quick': 'time-asc', 'climb': 'climb-desc' };
|
||||
var SORT_COLUMN = { 'name': 'name', 'name-desc': 'name', 'length-desc': 'length', 'length-asc': 'length',
|
||||
'time-asc': 'time', 'time-desc': 'time', 'climb-desc': 'climb', 'climb-asc': 'climb' };
|
||||
var SORT_ARROW = { 'name': '↑', 'name-desc': '↓', 'length-desc': '↓', 'length-asc': '↑',
|
||||
'time-asc': '↑', 'time-desc': '↓', 'climb-desc': '↓', 'climb-asc': '↑' };
|
||||
var COLUMN_PRIMARY = { 'name': 'name', 'length': 'length-desc', 'time': 'time-asc', 'climb': 'climb-desc' };
|
||||
var COLUMN_TOGGLE = { 'name': 'name-desc', 'name-desc': 'name', 'length-desc': 'length-asc', 'length-asc': 'length-desc',
|
||||
'time-asc': 'time-desc', 'time-desc': 'time-asc', 'climb-desc': 'climb-asc', 'climb-asc': 'climb-desc' };
|
||||
|
||||
function normalizeSortKey(value, dflt) {
|
||||
if (SORT_KEYS[value]) return value;
|
||||
if (SORT_OLD[value]) return SORT_OLD[value];
|
||||
return SORT_KEYS[dflt] ? dflt : 'name';
|
||||
}
|
||||
function cmpStr(a, b) { return a < b ? -1 : a > b ? 1 : 0; }
|
||||
function cmpNum(a, b) { return a < b ? -1 : a > b ? 1 : 0; }
|
||||
|
||||
function compareEntries(a, b, key) {
|
||||
key = normalizeSortKey(key, 'name');
|
||||
var an = a.dataset.name || '', bn = b.dataset.name || '';
|
||||
if (key === 'name') return cmpStr(an, bn);
|
||||
if (key === 'name-desc') return cmpStr(bn, an);
|
||||
if (key === 'climb-desc' || key === 'climb-asc') {
|
||||
var ac = a.dataset.climb === '' || a.dataset.climb == null ? null : Number(a.dataset.climb);
|
||||
var bc = b.dataset.climb === '' || b.dataset.climb == null ? null : Number(b.dataset.climb);
|
||||
if (ac === null || bc === null) {
|
||||
if (ac === null && bc === null) return cmpStr(an, bn);
|
||||
return ac === null ? 1 : -1;
|
||||
}
|
||||
return (key === 'climb-desc' ? cmpNum(bc, ac) : cmpNum(ac, bc)) || cmpStr(an, bn);
|
||||
}
|
||||
var av = Number(key.indexOf('length') === 0 ? a.dataset.km : a.dataset.days);
|
||||
var bv = Number(key.indexOf('length') === 0 ? b.dataset.km : b.dataset.days);
|
||||
return (key.slice(-5) === '-desc' ? cmpNum(bv, av) : cmpNum(av, bv)) || cmpStr(an, bn);
|
||||
}
|
||||
|
||||
function sortEntriesIn(root, key) {
|
||||
root.querySelectorAll('ol.entries').forEach(function (list) {
|
||||
Array.prototype.slice.call(list.querySelectorAll('.entry'))
|
||||
.sort(function (a, b) { return compareEntries(a, b, key); })
|
||||
.forEach(function (li) { list.appendChild(li); });
|
||||
});
|
||||
}
|
||||
|
||||
function defaultSortOf(root) {
|
||||
return normalizeSortKey(root && root.dataset ? root.dataset.defaultSort : '', 'name');
|
||||
}
|
||||
|
||||
function syncSortHeads(root, key) {
|
||||
root.querySelectorAll('[data-sort-col]').forEach(function (btn) {
|
||||
var active = SORT_COLUMN[key] === btn.dataset.sortCol;
|
||||
btn.classList.toggle('is-active', active);
|
||||
var arrow = btn.querySelector('[data-arrow]');
|
||||
if (arrow) arrow.textContent = active ? SORT_ARROW[key] : '↕';
|
||||
});
|
||||
}
|
||||
|
||||
function announceSort(root, key) {
|
||||
if (!root) return;
|
||||
var status = root.querySelector('[data-sort-status]');
|
||||
var select = root.querySelector('[data-sort-select]');
|
||||
if (!status || !select) return;
|
||||
var label = key;
|
||||
Array.prototype.forEach.call(select.options, function (o) { if (o.value === key) label = o.textContent; });
|
||||
var text = 'Sorted by ' + label + '.';
|
||||
if (status.textContent !== text) status.textContent = text;
|
||||
}
|
||||
|
||||
function applySortUI(root, key, announce) {
|
||||
key = normalizeSortKey(key, defaultSortOf(root));
|
||||
sortEntriesIn(root, key);
|
||||
var select = root.querySelector('[data-sort-select]');
|
||||
if (select && select.value !== key) select.value = key;
|
||||
syncSortHeads(root, key);
|
||||
if (announce) announceSort(root, key);
|
||||
return key;
|
||||
}
|
||||
|
||||
function nextSortForColumn(col, current) {
|
||||
current = normalizeSortKey(current, 'name');
|
||||
return SORT_COLUMN[current] === col ? COLUMN_TOGGLE[current] : COLUMN_PRIMARY[col];
|
||||
}
|
||||
|
||||
function wireSortHeads(root, getKey, setKey) {
|
||||
root.querySelectorAll('[data-sort-col]').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () { setKey(nextSortForColumn(btn.dataset.sortCol, getKey())); });
|
||||
});
|
||||
}
|
||||
|
||||
function sortFromUrl(root) {
|
||||
return normalizeSortKey(new URLSearchParams(window.location.search).get('sort'), defaultSortOf(root));
|
||||
}
|
||||
|
||||
function replaceSortInUrl(root, key) {
|
||||
var p = new URLSearchParams(window.location.search);
|
||||
if (key === defaultSortOf(root)) p.delete('sort'); else p.set('sort', key);
|
||||
var q = p.toString();
|
||||
window.history.replaceState(null, '', (q ? '?' + q : window.location.pathname) + window.location.hash);
|
||||
}
|
||||
|
||||
function initSortableLists() {
|
||||
document.querySelectorAll('.results[data-sortable]').forEach(function (root) {
|
||||
if (root.querySelector('#entries')) return; /* the finder wires its own list */
|
||||
var select = root.querySelector('[data-sort-select]');
|
||||
var current = defaultSortOf(root);
|
||||
function setSort(key, updateUrl, announce) {
|
||||
current = applySortUI(root, key, announce);
|
||||
if (updateUrl) replaceSortInUrl(root, current);
|
||||
}
|
||||
if (select) select.addEventListener('change', function () { setSort(select.value, true, true); });
|
||||
wireSortHeads(root, function () { return current; }, function (k) { setSort(k, true, true); });
|
||||
setSort(sortFromUrl(root), false, false);
|
||||
window.addEventListener('popstate', function () { setSort(sortFromUrl(root), false, false); });
|
||||
});
|
||||
}
|
||||
|
||||
/* 3. Trail finder (home page) ------------------------------------------------
|
||||
The filters are the attributes every page names: Where, Length, Time,
|
||||
Season, Terrain, Kind, Walking, Shape and GPX. Each row carries its values
|
||||
@@ -575,9 +794,11 @@
|
||||
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 resultsRoot = list.closest('.results');
|
||||
var listHead = resultsRoot ? resultsRoot.querySelector('.list-head') : document.querySelector('.list-head');
|
||||
var el = form.elements;
|
||||
var sort = document.getElementById('sort');
|
||||
var defaultSort = defaultSortOf(resultsRoot);
|
||||
var more = form.querySelector('.filters__more');
|
||||
var total = items.length;
|
||||
|
||||
@@ -687,7 +908,7 @@
|
||||
if (s.month) p.set('month', s.month);
|
||||
if (s.kind) p.set('kind', s.kind);
|
||||
MULTI.forEach(function (name) { if (s[name].length) p.set(name, s[name].join(',')); });
|
||||
if (sort.value !== 'name') p.set('sort', sort.value);
|
||||
if (sort.value !== defaultSort) p.set('sort', sort.value);
|
||||
return p.toString();
|
||||
}
|
||||
|
||||
@@ -712,24 +933,11 @@
|
||||
MULTI.forEach(function (name) {
|
||||
boxes(name).forEach(function (b) { b.checked = lists[name].indexOf(b.value) !== -1; });
|
||||
});
|
||||
var s = p.get('sort') || 'name';
|
||||
sort.value = hasOption(sort, s) ? s : 'name';
|
||||
sort.value = normalizeSortKey(p.get('sort'), defaultSort);
|
||||
}
|
||||
|
||||
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);
|
||||
if (key === 'quick') return Number(a.dataset.days) - Number(b.dataset.days) || Number(a.dataset.km) - Number(b.dataset.km);
|
||||
if (key === 'climb') {
|
||||
/* Most climb first; a trail with no computed climb goes last. */
|
||||
var ac = a.dataset.climb === '' ? -1 : Number(a.dataset.climb);
|
||||
var bc = b.dataset.climb === '' ? -1 : Number(b.dataset.climb);
|
||||
return bc - ac || a.dataset.name.localeCompare(b.dataset.name);
|
||||
}
|
||||
return a.dataset.name.localeCompare(b.dataset.name);
|
||||
}).forEach(function (li) { list.appendChild(li); });
|
||||
if (resultsRoot) applySortUI(resultsRoot, sort.value, false);
|
||||
}
|
||||
|
||||
function apply(updateUrl) {
|
||||
@@ -776,7 +984,10 @@
|
||||
document.querySelectorAll('[data-reset]').forEach(function (b) {
|
||||
b.addEventListener('click', function () { form.reset(); el.q.focus(); });
|
||||
});
|
||||
sort.addEventListener('change', function () { applySort(); apply(true); });
|
||||
sort.addEventListener('change', function () { applySort(); apply(true); announceSort(resultsRoot, sort.value); });
|
||||
if (resultsRoot) wireSortHeads(resultsRoot, function () { return sort.value; }, function (k) {
|
||||
sort.value = k; applySort(); apply(true); announceSort(resultsRoot, sort.value);
|
||||
});
|
||||
document.addEventListener('olt:units', relabelLengths);
|
||||
|
||||
items.forEach(function (li) {
|
||||
@@ -805,6 +1016,7 @@
|
||||
|
||||
var finder = document.getElementById('finder-form');
|
||||
if (finder) initFinder(finder);
|
||||
initSortableLists();
|
||||
|
||||
/* 4. A link to a part of the page inside a closed <details> (About this data)
|
||||
opens it, so the target is shown rather than hidden. */
|
||||
|
||||
+33
-2
@@ -417,6 +417,9 @@ code.raw {
|
||||
border: 1px solid var(--rule-strong);
|
||||
background: var(--hatch-fill);
|
||||
}
|
||||
.swatch--sketch {
|
||||
background: radial-gradient(circle at center, var(--ink-2) 1.7px, transparent 1.8px) 0 50% / 7px 100% repeat-x;
|
||||
}
|
||||
|
||||
/* Logo plate: a light sign board so every logo reads as drawn */
|
||||
.plate {
|
||||
@@ -630,6 +633,10 @@ code.raw {
|
||||
.fallback__line { stroke: var(--trail); stroke-width: 2.25; fill: none; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; }
|
||||
.fallback__line--route { stroke: var(--route); stroke-dasharray: 5 3; }
|
||||
.fallback__line--alternate { stroke-width: 1.5; stroke-dasharray: 4 3; }
|
||||
.fallback__line--sketch { stroke-width: 2.5; stroke-dasharray: 0.1 5; stroke-linecap: round; }
|
||||
.fallback__line--sketch-route { stroke: var(--route); }
|
||||
.fallback__ring { fill: var(--casing); stroke: var(--trail); stroke-width: 2; vector-effect: non-scaling-stroke; }
|
||||
.fallback__ring--route { stroke: var(--route); }
|
||||
|
||||
.mapfig__caption {
|
||||
display: flex;
|
||||
@@ -644,6 +651,11 @@ code.raw {
|
||||
.mapfig__caption strong { color: var(--ink); font-weight: 600; }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-4); padding: 0; list-style: none; }
|
||||
.legend li { display: inline-flex; align-items: center; gap: var(--space-2); }
|
||||
/* Under a map of many trails the legend keeps a row to itself, however short it is. */
|
||||
.mapfig[data-map="overview"] .legend { flex-basis: 100%; }
|
||||
.mapfig__caption--sketch { align-items: start; }
|
||||
.sketch-note { display: grid; gap: var(--space-2); max-inline-size: 42rem; }
|
||||
.sketch-note .cluster { margin-block-start: var(--space-1); }
|
||||
|
||||
/* Empty frame: the record has no line, so nothing is drawn */
|
||||
.map--empty {
|
||||
@@ -889,8 +901,14 @@ code.raw {
|
||||
}
|
||||
.results-count { font: 400 var(--step-0)/1.3 var(--font-sans); color: var(--ink-2); }
|
||||
.results-count strong { color: var(--ink); font-size: var(--step-2); font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.results-sort { display: flex; align-items: center; gap: var(--space-2); font: 600 var(--step--2) var(--font-sans); letter-spacing: 0.08em; text-transform: uppercase; }
|
||||
.results-sort .select { inline-size: auto; min-block-size: 2.75rem; letter-spacing: 0; text-transform: none; font-weight: 400; }
|
||||
.results-sort { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-3); font: 500 var(--step-0)/1.3 var(--font-sans); color: var(--ink); }
|
||||
.results-sort__label { font-weight: 600; }
|
||||
.results-sort .select { inline-size: auto; min-block-size: 2.75rem; font-weight: 500; }
|
||||
@media (max-width: 40rem) {
|
||||
.results-tools { flex-basis: 100%; }
|
||||
.results-sort { flex: 1 1 100%; }
|
||||
.results-sort .select { flex: 1 1 auto; }
|
||||
}
|
||||
.key {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -911,6 +929,8 @@ code.raw {
|
||||
html:not(.js) .filters,
|
||||
html:not(.js) .results-tools { display: none; }
|
||||
html:not(.js) .finder__grid { grid-template-areas: "main" "notes"; grid-template-columns: minmax(0, 1fr); }
|
||||
html:not(.js) .list-head__sort { cursor: default; }
|
||||
html:not(.js) .list-head__arrow { display: none; }
|
||||
|
||||
/* Trail list: a gazetteer. One row per record. The list is its own inline-size
|
||||
container (named as the results wrapper is) so rows take the column layout
|
||||
@@ -1068,6 +1088,17 @@ html:not(.js) .finder__grid { grid-template-areas: "main" "notes"; grid-template
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.list-head > :first-child { grid-column: 2; }
|
||||
.list-head__sort {
|
||||
display: inline-flex; align-items: baseline; gap: var(--space-1);
|
||||
margin: 0; padding: var(--space-1) 0; border: 0; background: none;
|
||||
color: inherit; font: inherit; letter-spacing: inherit; text-transform: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.list-head__plain { padding-block: var(--space-1); }
|
||||
.list-head__sort:hover { color: var(--ink); text-decoration: underline; text-underline-offset: 0.16em; }
|
||||
.list-head__sort.is-active { color: var(--ink); }
|
||||
.list-head__arrow { color: var(--ink-2); font-size: 1.25em; line-height: 1; letter-spacing: 0; }
|
||||
.list-head__sort.is-active .list-head__arrow { color: var(--trail); }
|
||||
.list-head__scale { position: relative; display: block; block-size: 1em; margin-block-start: var(--space-1); font: 400 0.6875rem/1 var(--font-mono); letter-spacing: 0; text-transform: none; }
|
||||
.list-head__scale > span { position: absolute; transform: translateX(-50%); white-space: nowrap; }
|
||||
.list-head__scale > span:nth-child(1) { inset-inline-start: 10.8%; }
|
||||
|
||||
+36
-7
@@ -19,7 +19,7 @@ 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
|
||||
from olt import geo, hike, records # noqa: E402
|
||||
|
||||
GPX_TOL_M = 5.0
|
||||
MAP_TOL_M = 30.0
|
||||
@@ -27,6 +27,7 @@ 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", "hike.py"),
|
||||
os.path.join(HERE, "olt", "records.py")]
|
||||
# Incremental-build cache, deliberately outside the publish directory.
|
||||
CACHE_DIR = os.path.join(HERE, ".cache")
|
||||
@@ -92,7 +93,26 @@ def multiline_feature(parts, props):
|
||||
"geometry": {"type": "MultiLineString", "coordinates": parts}}
|
||||
|
||||
|
||||
def trail_outputs(tid, files):
|
||||
def sketch_features(rec):
|
||||
"""GeoJSON features sketching a trail with no track from its start and
|
||||
end points, or the one on file: a straight LineString when both are known, and a MultiPoint
|
||||
for the rings at the ends. Marked sketch, never a track: no download,
|
||||
no GPX status and no elevation ever come from these."""
|
||||
points = hike.sketch_points(rec)
|
||||
if not points:
|
||||
return []
|
||||
props = {"id": rec["id"], "name": rec["name"], "kind": rec["derived"]["kind"],
|
||||
"country": rec["country"], "length_km": rec["length_km"], "sketch": True}
|
||||
features = []
|
||||
if len(points) == 2:
|
||||
features.append({"type": "Feature", "properties": dict(props),
|
||||
"geometry": {"type": "LineString", "coordinates": points}})
|
||||
features.append({"type": "Feature", "properties": dict(props),
|
||||
"geometry": {"type": "MultiPoint", "coordinates": points}})
|
||||
return features
|
||||
|
||||
|
||||
def trail_outputs(tid, files, rec=None):
|
||||
"""Names of the data files written into _site/trails/<id>/ for these files."""
|
||||
names = []
|
||||
if "line" in files:
|
||||
@@ -103,6 +123,8 @@ def trail_outputs(tid, files):
|
||||
names.append(f"{tid}-{src}.geojson")
|
||||
if "line" in files or "alternates" in files:
|
||||
names.append("map.json")
|
||||
if rec is not None and "line" not in files and hike.sketch_points(rec):
|
||||
names.append("sketch.json")
|
||||
if "shield" in files:
|
||||
names.append(os.path.basename(files["shield"]))
|
||||
return names
|
||||
@@ -111,7 +133,7 @@ def trail_outputs(tid, files):
|
||||
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
|
||||
return name in ("map.json", "sketch.json") or name.endswith((".geojson", ".gpx")) or name in records.SHIELD_NAMES
|
||||
|
||||
|
||||
def remove_stale(tdir, expected):
|
||||
@@ -134,7 +156,7 @@ def read_cache(cache_path):
|
||||
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)
|
||||
names = trail_outputs(rec["id"], files, rec)
|
||||
cache = read_cache(cache_path)
|
||||
if cache is None or cache.get("outputs") != sorted(names):
|
||||
return False
|
||||
@@ -183,7 +205,7 @@ def build_trail(rec, out_dir, code_mtime, force, stats):
|
||||
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)
|
||||
names = trail_outputs(tid, files, rec)
|
||||
cache = {}
|
||||
|
||||
if not names:
|
||||
@@ -223,10 +245,15 @@ def build_trail(rec, out_dir, code_mtime, force, stats):
|
||||
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)
|
||||
sketches = sketch_features(rec) if "line" not in files else []
|
||||
if sketches:
|
||||
box = hike.sketch_bbox(hike.sketch_points(rec), pad=True)
|
||||
write_json(os.path.join(tdir, "sketch.json"),
|
||||
{"type": "FeatureCollection", "bbox": box, "features": sketches}, 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)
|
||||
names = trail_outputs(tid, files, rec)
|
||||
cache = dict(cache, outputs=sorted(names), creator=gpx_creator())
|
||||
if names:
|
||||
with open(cache_path, "w", encoding="utf-8") as f:
|
||||
@@ -271,10 +298,12 @@ def read_main_map_parts(tdir):
|
||||
|
||||
|
||||
def overview_geojson(recs, out_dir):
|
||||
"""One MultiLineString per included trail, simplified from the 30 m map line."""
|
||||
"""One MultiLineString per included trail, simplified from the 30 m map line.
|
||||
A trail with no track but a known start or end appears as sketch features."""
|
||||
features = []
|
||||
for rec in recs:
|
||||
if "line" not in rec["derived"]["files"]:
|
||||
features.extend(sketch_features(rec))
|
||||
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
|
||||
|
||||
+8
-11
@@ -30,8 +30,9 @@ class List:
|
||||
title: str
|
||||
blurb: str
|
||||
test: Callable[[dict], bool]
|
||||
# Order within the list: longest first unless a list says otherwise.
|
||||
order: Callable[[dict], object] = lambda r: -r["length_km"]
|
||||
# The order the list opens in, a key of facets.SORTS. Name order unless
|
||||
# the list is defined by an order (the longest, the shortest, a week).
|
||||
sort: str = "name"
|
||||
|
||||
|
||||
def _mi(km):
|
||||
@@ -42,10 +43,6 @@ def _band(key):
|
||||
return lambda r: facets.time_band(r) == key
|
||||
|
||||
|
||||
def _days(r):
|
||||
return facets.time_days(r)[1]
|
||||
|
||||
|
||||
LISTS = (
|
||||
List("national-scenic-trails", "National Scenic Trails",
|
||||
"The long trails the United States Congress has named National Scenic Trails.",
|
||||
@@ -54,16 +51,16 @@ LISTS = (
|
||||
lambda r: facets.kind(r) == "route"),
|
||||
List("longest", "The longest",
|
||||
f"Trails of {LONG_KM:,} km ({_mi(LONG_KM)} mi) or more.",
|
||||
lambda r: r["length_km"] >= LONG_KM),
|
||||
lambda r: r["length_km"] >= LONG_KM, sort="length-desc"),
|
||||
List("under-100-km", f"Under {SHORT_KM} km",
|
||||
f"Trails shorter than {SHORT_KM} km ({_mi(SHORT_KM)} mi).",
|
||||
lambda r: r["length_km"] < SHORT_KM, order=lambda r: r["length_km"]),
|
||||
lambda r: r["length_km"] < SHORT_KM, sort="length-asc"),
|
||||
List("a-week-or-less", "A week or less",
|
||||
"Trails most people walk in a week or less, as a source states it or as estimated from the length.",
|
||||
_band("week"), order=_days),
|
||||
_band("week"), sort="time-asc"),
|
||||
List("one-to-two-weeks", "One to two weeks",
|
||||
"Trails that take one to two weeks, as a source states it or as estimated from the length.",
|
||||
_band("two-weeks"), order=_days),
|
||||
_band("two-weeks"), sort="time-asc"),
|
||||
List("loops", "Loops", "Trails that finish where they start.",
|
||||
lambda r: facets.shape(r) == "loop"),
|
||||
List("with-gpx", "With a GPX to download",
|
||||
@@ -84,7 +81,7 @@ LISTS = (
|
||||
|
||||
|
||||
def members(lst, records):
|
||||
return sorted((r for r in records if lst.test(r)), key=lambda r: (lst.order(r), r["name"]))
|
||||
return facets.sort_records([r for r in records if lst.test(r)], lst.sort)
|
||||
|
||||
|
||||
def is_shown(n, total):
|
||||
|
||||
@@ -180,6 +180,8 @@ SWATCH_LINE = Markup('<span class="swatch swatch--line" aria-hidden="true"></spa
|
||||
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>')
|
||||
# A trail with no track, sketched from its start (and end) points only.
|
||||
SWATCH_SKETCH = Markup('<span class="swatch swatch--sketch" 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>')
|
||||
|
||||
+4
-1
@@ -384,7 +384,9 @@ BULK_FILES = (
|
||||
("trails.json", "Every record in full, as JSON, with the derived fields the site builds.", False),
|
||||
("index.geojson", "Every included track, simplified to about 100 m, with id and name.", True),
|
||||
("overview.geojson", "Every included track simplified to about 750 m for the overview map, "
|
||||
"with id, name, kind, country and length.", False),
|
||||
"with id, name, kind, country and length. A trail with no track but a known "
|
||||
"start or end appears marked as a sketch: a straight line between the two, "
|
||||
"or one point alone. A sketch is not a track.", False),
|
||||
("all-gpx.zip", "Every GPX file (main tracks 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 track and alternates file, as <id>/<file>, "
|
||||
@@ -432,6 +434,7 @@ def data_page(records, site, repo_root, out_dir):
|
||||
("<id>-alternates.geojson / .gpx", "Alternate and connector tracks, where the source serves them separately."),
|
||||
("<id>-<source>.geojson", "One source's own extract, where a track combines sources."),
|
||||
("map.json", "The track simplified to 30 m for the trail page map (GeoJSON)."),
|
||||
("sketch.json", "Start and end points only, for the trail page map where there is no track (GeoJSON). Not a track."),
|
||||
("trail.toml", "The record itself: source, licence, verification, logo and route details."),
|
||||
("release.txt", "The source, licence and date the track files came from, where a track is included."),
|
||||
("shield.svg / shield.png", "The trail logo, where one is included. Not licensed; see Logos."),
|
||||
|
||||
+85
-1
@@ -17,8 +17,10 @@ attributes a hiker filters by; they stay in "About this data" on each trail
|
||||
page and on the pages under About.
|
||||
"""
|
||||
import math
|
||||
import re
|
||||
from functools import cmp_to_key
|
||||
|
||||
from . import common, hike, words
|
||||
from . import common, elevation, hike, words
|
||||
|
||||
# Facet names, exactly as every page shows them.
|
||||
WHERE, LENGTH, TIME, SEASON, TERRAIN, KIND, WALKING, SHAPE, GPX = (
|
||||
@@ -308,3 +310,85 @@ def missing_text(n, key):
|
||||
if not n:
|
||||
return ""
|
||||
return f"{n} trail{'s' if n != 1 else ''} {'has' if n == 1 else 'have'} no {MISSING_NOUN[key]} on file."
|
||||
|
||||
|
||||
# Sorting ----------------------------------------------------------------------
|
||||
# The one definition of each list order. app.js holds the same orders over the
|
||||
# rows' data-* attributes; test_sorting checks the two agree.
|
||||
|
||||
SORTS = (
|
||||
("name", "Name, A to Z"),
|
||||
("name-desc", "Name, Z to A"),
|
||||
("length-desc", "Length, longest first"),
|
||||
("length-asc", "Length, shortest first"),
|
||||
("time-asc", "Time, quickest first"),
|
||||
("time-desc", "Time, slowest first"),
|
||||
("climb-desc", "Climb, most first"),
|
||||
("climb-asc", "Climb, least first"),
|
||||
)
|
||||
SORT_LABEL = dict(SORTS)
|
||||
# Keys older addresses used, still honoured.
|
||||
OLD_SORTS = {"long": "length-desc", "short": "length-asc",
|
||||
"quick": "time-asc", "climb": "climb-desc"}
|
||||
|
||||
|
||||
def sort_name(rec):
|
||||
return re.sub(r"^The ", "", rec["name"]).lower()
|
||||
|
||||
|
||||
def normalize_sort(key, default="name"):
|
||||
"""A sort key from SORTS: key itself, its modern spelling, else default."""
|
||||
if key in SORT_LABEL:
|
||||
return key
|
||||
if key in OLD_SORTS:
|
||||
return OLD_SORTS[key]
|
||||
return default if default in SORT_LABEL else "name"
|
||||
|
||||
|
||||
def row_climb_m(rec):
|
||||
"""The climb a list row may show and sort by, in metres, or None.
|
||||
|
||||
A climb from a track that covers only part of the trail, or more than
|
||||
the trail, would mislead in a list, so it counts as no climb here.
|
||||
"""
|
||||
elev = elevation.get(rec)
|
||||
if elev and elevation.coverage_kind(elev):
|
||||
return None
|
||||
return elev["ascent_m"] if elev else None
|
||||
|
||||
|
||||
def sort_values(rec):
|
||||
"""(name, km, days, climb) exactly as the row's data-* attributes carry them."""
|
||||
return (sort_name(rec), rec["length_km"], time_days(rec)[1], row_climb_m(rec))
|
||||
|
||||
|
||||
def _cmp(a, b):
|
||||
return (a > b) - (a < b)
|
||||
|
||||
|
||||
def compare_values(va, vb, key):
|
||||
"""Order two sort_values tuples under key. Ties fall back to name;
|
||||
a trail with no climb goes last in both climb orders."""
|
||||
key = normalize_sort(key)
|
||||
if key == "name":
|
||||
return _cmp(va[0], vb[0])
|
||||
if key == "name-desc":
|
||||
return _cmp(vb[0], va[0])
|
||||
if key.startswith("climb"):
|
||||
ca, cb = va[3], vb[3]
|
||||
if ca is None or cb is None:
|
||||
if ca is None and cb is None:
|
||||
return _cmp(va[0], vb[0])
|
||||
return 1 if ca is None else -1
|
||||
order = _cmp(cb, ca) if key == "climb-desc" else _cmp(ca, cb)
|
||||
return order or _cmp(va[0], vb[0])
|
||||
i = 1 if key.startswith("length") else 2
|
||||
order = _cmp(vb[i], va[i]) if key.endswith("-desc") else _cmp(va[i], vb[i])
|
||||
return order or _cmp(va[0], vb[0])
|
||||
|
||||
|
||||
def sort_records(records, key="name"):
|
||||
"""The records in the order key names, as a new list."""
|
||||
key = normalize_sort(key)
|
||||
values = {id(r): sort_values(r) for r in records}
|
||||
return sorted(records, key=cmp_to_key(lambda a, b: compare_values(values[id(a)], values[id(b)], key)))
|
||||
@@ -3,6 +3,7 @@
|
||||
Every field is optional, and most records have no [hike] table at all, so
|
||||
every function here returns "" (or an empty list) when its field is missing.
|
||||
"""
|
||||
import math
|
||||
import re
|
||||
|
||||
from . import words
|
||||
@@ -93,3 +94,71 @@ def ends(rec):
|
||||
|
||||
def sources(rec):
|
||||
return [s for s in table(rec).get("source", []) if isinstance(s, dict)]
|
||||
|
||||
|
||||
def _lonlat(value):
|
||||
"""A [lon, lat] pair as floats, or None when it is missing or not a place on Earth."""
|
||||
if not isinstance(value, (list, tuple)) or len(value) < 2:
|
||||
return None
|
||||
lon, lat = value[0], value[1]
|
||||
if isinstance(lon, bool) or isinstance(lat, bool):
|
||||
return None
|
||||
if not isinstance(lon, (int, float)) or not isinstance(lat, (int, float)):
|
||||
return None
|
||||
lon, lat = float(lon), float(lat)
|
||||
if not (-180.0 <= lon <= 180.0 and -90.0 <= lat <= 90.0):
|
||||
return None
|
||||
return [lon, lat]
|
||||
|
||||
|
||||
def start_point(rec):
|
||||
"""[lon, lat] of the place named in [hike].start, or None."""
|
||||
return _lonlat(table(rec).get("start_lonlat"))
|
||||
|
||||
|
||||
def end_point(rec):
|
||||
"""[lon, lat] of the place named in [hike].end, or None. A loop has none."""
|
||||
return _lonlat(table(rec).get("end_lonlat"))
|
||||
|
||||
|
||||
def sketch_points(rec):
|
||||
"""The points a map may sketch for a trail with no track: [start, end]
|
||||
when both are on file, or the one that is. Empty when the trail has a
|
||||
track or neither point (see sketch_end for which end a lone point is).
|
||||
|
||||
A sketch is only ever these points. It is never a track: nothing here
|
||||
feeds a download, a GPX status or an elevation figure.
|
||||
"""
|
||||
derived = rec.get("derived", {})
|
||||
if derived.get("has_line") or "line" in derived.get("files", {}):
|
||||
return []
|
||||
points = [p for p in (start_point(rec), end_point(rec)) if p]
|
||||
return points[:1] if len(points) == 2 and points[0] == points[1] else points
|
||||
|
||||
|
||||
def sketch_end(rec):
|
||||
""""start" or "end": which end a one-point sketch marks. "" otherwise."""
|
||||
if len(sketch_points(rec)) != 1:
|
||||
return ""
|
||||
return "start" if start_point(rec) else "end"
|
||||
|
||||
|
||||
def sketch_bbox(points, *, pad=False):
|
||||
"""[min lon, min lat, max lon, max lat] of sketch points, or None.
|
||||
|
||||
pad: widen for framing a map. One point gets about a county of ground;
|
||||
two points get a margin around the pair.
|
||||
"""
|
||||
if not points:
|
||||
return None
|
||||
box = [min(p[0] for p in points), min(p[1] for p in points),
|
||||
max(p[0] for p in points), max(p[1] for p in points)]
|
||||
if not pad:
|
||||
return box
|
||||
if len(points) == 1:
|
||||
lat_pad = 0.35
|
||||
lon_pad = 0.35 / max(math.cos(math.radians(points[0][1])), 0.25)
|
||||
else:
|
||||
lat_pad = max((box[3] - box[1]) * 0.12, 0.05)
|
||||
lon_pad = max((box[2] - box[0]) * 0.12, 0.05)
|
||||
return [box[0] - lon_pad, box[1] - lat_pad, box[2] + lon_pad, box[3] + lat_pad]
|
||||
+136
-48
@@ -6,9 +6,8 @@ attributes in olt/facets.py, under the same names the trail pages use.
|
||||
"""
|
||||
import collections
|
||||
import math
|
||||
import re
|
||||
|
||||
from . import browse, common, elevation, facets, hike, words
|
||||
from . import browse, common, facets, hike, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
# Length range choices (km) for the filters. length_steps() adds a top step
|
||||
@@ -51,16 +50,19 @@ def counts(records):
|
||||
|
||||
|
||||
def overview_bbox(records):
|
||||
"""data-bbox attribute: the extent of every track, so the map opens on it before the data loads."""
|
||||
"""data-bbox attribute: the extent of every track and sketch, so the map opens on it before the data loads."""
|
||||
boxes = [r["derived"]["bbox"] for r in records if r["derived"].get("bbox")]
|
||||
for r in records:
|
||||
box = hike.sketch_bbox(hike.sketch_points(r))
|
||||
if box:
|
||||
boxes.append(box)
|
||||
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()
|
||||
sort_name = facets.sort_name
|
||||
|
||||
|
||||
# A row ------------------------------------------------------------------------
|
||||
@@ -111,15 +113,13 @@ def entry(rec, *, level=3, extra="", routes_list=False):
|
||||
lo, hi, est = facets.time_days(rec)
|
||||
search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"], facets.author(rec)]).lower()
|
||||
abbr_cls = "entry__abbr" if common.shield_url(rec) else "entry__abbr vh"
|
||||
elev = elevation.get(rec)
|
||||
# A climb worked out from a track that covers only part of the trail, or more
|
||||
# than the trail, would mislead in a list; the trail's own page gives it with
|
||||
# its caveat.
|
||||
if elev and elevation.coverage_kind(elev):
|
||||
elev = None
|
||||
# The climb a row may show and sort by (facets.row_climb_m): none when the
|
||||
# track covers too little or too much of the trail, so data-climb is empty
|
||||
# in exactly the cases where the row hides its climb.
|
||||
climb_m = facets.row_climb_m(rec)
|
||||
data = {
|
||||
"id": rec["id"], "where": " ".join(facets.where_tokens(rec)), "km": rec["length_km"],
|
||||
"climb": elev["ascent_m"] if elev else "",
|
||||
"climb": climb_m if climb_m is not None else "",
|
||||
"days": hi, "time": facets.time_band(rec), "months": " ".join(map(str, facets.months(rec))),
|
||||
"terrain": " ".join(facets.terrain(rec)), "kind": facets.kind(rec), "walking": facets.walking(rec),
|
||||
"shape": facets.shape(rec), "gpx": facets.gpx(rec), "name": sort_name(rec), "search": search.strip(),
|
||||
@@ -134,8 +134,8 @@ def entry(rec, *, level=3, extra="", routes_list=False):
|
||||
desc = entry_desc(rec)
|
||||
desc_html = f'\n <p class="entry__desc">{esc(desc)}</p>' if desc else ""
|
||||
time_html = esc(facets.time_text(rec)) + (' <small class="entry__est">estimate</small>' if est else "")
|
||||
climb_html = (f'\n <div class="entry__climb"><dt>Climb</dt><dd>{words.elevation(elev["ascent_m"], "stack")}'
|
||||
f'<small class="entry__est">computed</small></dd></div>') if elev else ""
|
||||
climb_html = (f'\n <div class="entry__climb"><dt>Climb</dt><dd>{words.elevation(climb_m, "stack")}'
|
||||
f'<small class="entry__est">computed</small></dd></div>') if climb_m is not None else ""
|
||||
return f"""<li class="entry"{attrs}>
|
||||
{common.plate(rec)}
|
||||
<div class="entry__body">{kicker}
|
||||
@@ -296,21 +296,48 @@ def finder_form(records, c=None, steps=None):
|
||||
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."""
|
||||
# Sort column of each sort key, and the arrow for its direction in the head.
|
||||
_SORT_COLUMN = {"name": "name", "name-desc": "name", "length-desc": "length",
|
||||
"length-asc": "length", "time-asc": "time", "time-desc": "time",
|
||||
"climb-desc": "climb", "climb-asc": "climb"}
|
||||
_SORT_ARROW = {"name": "↑", "name-desc": "↓", "length-desc": "↓", "length-asc": "↑",
|
||||
"time-asc": "↑", "time-desc": "↓", "climb-desc": "↓", "climb-asc": "↑"}
|
||||
|
||||
|
||||
def _head_button(col, label, sort_key, extra=""):
|
||||
active = _SORT_COLUMN[sort_key] == col
|
||||
arrow = _SORT_ARROW[sort_key] if active else "↕"
|
||||
cls = "list-head__sort is-active" if active else "list-head__sort"
|
||||
return (f'<span><button type="button" class="{cls}" data-sort-col="{col}" tabindex="-1">'
|
||||
f'{esc(label)} <span class="list-head__arrow" data-arrow aria-hidden="true">{arrow}</span>'
|
||||
f'</button>{extra}</span>')
|
||||
|
||||
|
||||
def list_head(sort_key="name"):
|
||||
"""The column head over a list: Trail, Length, Time and Climb are sort
|
||||
buttons; GPX is not sortable. The scale ticks follow the reader's unit
|
||||
preference with the same len__km / len__mi pair the lengths use.
|
||||
|
||||
The head stays aria-hidden with its buttons out of the tab order on
|
||||
purpose: the "Sort by" select in the results head is the one sort
|
||||
control for keyboard and screen-reader users, and app.js announces
|
||||
each new order beside it. The buttons are a pointer shortcut that
|
||||
always agrees with the select.
|
||||
"""
|
||||
sort_key = facets.normalize_sort(sort_key)
|
||||
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>')
|
||||
scale = f'<span class="list-head__scale">{"".join(ticks)}</span>'
|
||||
return f"""<div class="list-head" aria-hidden="true">
|
||||
<span>Trail</span>
|
||||
<span>{facets.LENGTH}<span class="list-head__scale">{"".join(ticks)}</span></span>
|
||||
<span>{facets.TIME}</span>
|
||||
<span>{facets.GPX}</span>
|
||||
<span>Climb</span>
|
||||
{_head_button("name", "Trail", sort_key)}
|
||||
{_head_button("length", facets.LENGTH, sort_key, scale)}
|
||||
{_head_button("time", facets.TIME, sort_key)}
|
||||
<span class="list-head__plain">{facets.GPX}</span>
|
||||
{_head_button("climb", "Climb", sort_key)}
|
||||
</div>"""
|
||||
|
||||
|
||||
@@ -322,15 +349,22 @@ UNITS_TOGGLE = """<fieldset class="results-units">
|
||||
</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>
|
||||
<option value="quick">Quickest first</option>
|
||||
<option value="climb">Most climb first</option>
|
||||
def sort_select(default_sort="name"):
|
||||
"""The one sort control of every list of trails, with the page's
|
||||
default order selected. Hidden without JavaScript (style.css):
|
||||
it cannot work then, and the HTML is already in the default order."""
|
||||
default_sort = facets.normalize_sort(default_sort)
|
||||
options = "".join(
|
||||
f'\n <option value="{esc(k)}"{" selected" if k == default_sort else ""}>{esc(label)}</option>'
|
||||
for k, label in facets.SORTS)
|
||||
return f"""<label class="results-sort"><span class="results-sort__label">Sort by</span>
|
||||
<select class="select" id="sort" name="sort" data-sort-select>{options}
|
||||
</select>
|
||||
</label>"""
|
||||
</label>
|
||||
<span class="vh" data-sort-status aria-live="polite"></span>"""
|
||||
|
||||
|
||||
SORT_SELECT = sort_select()
|
||||
|
||||
|
||||
def key(official=True):
|
||||
@@ -342,16 +376,24 @@ def key(official=True):
|
||||
</ul>"""
|
||||
|
||||
|
||||
def results(recs=None, *, finder=False, groups=None, routes_list=False):
|
||||
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name"):
|
||||
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
|
||||
|
||||
finder: the home page's list, driven by the filters (live count, sort, empty state).
|
||||
Every list carries the same "Sort by" control. The rows are written in
|
||||
default_sort order (a key of facets.SORTS), so the page is right with
|
||||
JavaScript off; app.js reorders in place and keeps ?sort= in the address.
|
||||
|
||||
finder: the home page's list, driven by the filters (live count, empty state).
|
||||
groups: [(heading, trails, extra_fn)] to list the trails under level-3 headings;
|
||||
sorting is within each group and the groups keep their order.
|
||||
extra_fn(rec) gives HTML placed last in each row.
|
||||
routes_list: passed to entry() for the Routes list (see there).
|
||||
"""
|
||||
default_sort = facets.normalize_sort(default_sort)
|
||||
if groups is None:
|
||||
groups = [(None, recs, None)]
|
||||
groups = [(heading, facets.sort_records(list(items), default_sort), extra_fn)
|
||||
for heading, items, extra_fn in groups]
|
||||
total = sum(len(g[1]) for g in groups)
|
||||
shown = [r for g in groups for r in g[1]]
|
||||
only_routes = bool(shown) and all(facets.kind(r) == "route" for r in shown)
|
||||
@@ -368,7 +410,6 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False):
|
||||
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 trails match these filters.</strong></p>
|
||||
@@ -376,9 +417,9 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False):
|
||||
</div>"""
|
||||
else:
|
||||
count = f'<p class="results-count"><strong>{total}</strong> {noun}</p>'
|
||||
tools = UNITS_TOGGLE
|
||||
empty = ""
|
||||
return Markup(f"""<div class="results">
|
||||
tools = sort_select(default_sort) + "\n " + UNITS_TOGGLE
|
||||
return Markup(f"""<div class="results" data-sortable data-default-sort="{esc(default_sort)}">
|
||||
<div class="results-head">
|
||||
{count}
|
||||
<div class="results-tools">
|
||||
@@ -386,28 +427,70 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False):
|
||||
</div>
|
||||
</div>
|
||||
{key(official=not only_routes)}
|
||||
{list_head()}{lists}{empty}
|
||||
{list_head(default_sort)}{lists}{empty}
|
||||
</div>""")
|
||||
|
||||
|
||||
# A map of a selection is drawn only when it has at least this many tracks.
|
||||
# A map of a selection is drawn only when it has at least this many things
|
||||
# to draw: a track, or a sketch from a start or end point (hike.sketch_points).
|
||||
MAP_MIN = 3
|
||||
|
||||
|
||||
def track_ids(recs):
|
||||
return [r["id"] for r in recs if "line" in r["derived"]["files"]]
|
||||
|
||||
|
||||
def sketch_records(recs):
|
||||
"""Trails with no track that a map can sketch from their start or end point."""
|
||||
return [r for r in recs if hike.sketch_points(r)]
|
||||
|
||||
|
||||
def drawable_ids(recs):
|
||||
"""Ids a map of these trails can draw, by track or by sketch, in order."""
|
||||
tracks = set(track_ids(recs))
|
||||
return [r["id"] for r in recs if r["id"] in tracks or hike.sketch_points(r)]
|
||||
|
||||
|
||||
def overview_map(recs, label, *, wide=False, scope=""):
|
||||
"""The map of the given trails' tracks (the overview geometry, limited to their ids
|
||||
unless every trail is shown). "" when none of them has a track."""
|
||||
ids = [r["id"] for r in recs if "line" in r["derived"]["files"]]
|
||||
"""The map of the given trails (the overview geometry, limited to their ids
|
||||
unless every trail is shown). A note instead when too little can be drawn."""
|
||||
ids = drawable_ids(recs)
|
||||
if not ids:
|
||||
return Markup('<p class="note">None of these trails has a GPX here, so there is no track to draw. '
|
||||
'Each trail’s page says where to get one.</p>')
|
||||
return Markup('<p class="note">None of these trails has a GPX here or a known start or end, '
|
||||
'so there is nothing to draw. Each trail’s page says where to get a GPX.</p>')
|
||||
if len(ids) < MAP_MIN and scope != "all":
|
||||
names = words.join_names(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>'
|
||||
for r in recs if r["id"] in ids)
|
||||
return Markup(f'<p class="note">Only {names} {"has" if len(ids) == 1 else "have"} a GPX here, '
|
||||
'so no map of them all is drawn. Each trail’s page says where to get a track.</p>')
|
||||
return Markup(f'<p class="note">Only {names} {"has" if len(ids) == 1 else "have"} a GPX here '
|
||||
'or a known start or end, so no map of them all is drawn. '
|
||||
'Each trail’s page says where to get a track.</p>')
|
||||
ids_attr = "" if scope == "all" else f' data-ids="{esc(" ".join(ids))}"'
|
||||
n = len(ids)
|
||||
n = len(track_ids(recs))
|
||||
sketches = sketch_records(recs)
|
||||
# The legend names only what this map draws; the home page's map, which the
|
||||
# filters change, names every kind.
|
||||
drawn = [r for r in recs if r["id"] in set(ids)]
|
||||
legend = []
|
||||
if scope == "all" or any(not common.is_route(r) for r in drawn):
|
||||
legend.append(f"<li>{common.SWATCH_LINE}Official trail</li>")
|
||||
if scope == "all" or any(common.is_route(r) for r in drawn):
|
||||
legend.append(f"<li>{common.SWATCH_ROUTE}Route</li>")
|
||||
if sketches:
|
||||
legend.append(f"<li>{common.SWATCH_SKETCH}No GPX here: start and end only</li>")
|
||||
legend = "\n ".join(legend)
|
||||
sentences = []
|
||||
if n:
|
||||
sentences.append(f'{n} track{"s" if n != 1 else ""}, simplified for display. Select one for its name.')
|
||||
else:
|
||||
sentences.append("Select one for its name.")
|
||||
if sketches:
|
||||
s = len(sketches)
|
||||
sentences.append(f'{s} trail{"s" if s != 1 else ""} with no GPX here '
|
||||
f'{"are" if s != 1 else "is"} shown as a dotted straight line between '
|
||||
'their start and end, or a ring where only one end is known. '
|
||||
'That is not the trail’s path.')
|
||||
sentences.append("Each trail’s page names its source, credit and licence. "
|
||||
"Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.")
|
||||
return Markup(f"""<figure class="mapfig{" mapfig--wide" if wide else ""}" data-map="overview" data-src="/data/overview.geojson"{ids_attr}{overview_bbox(recs)}>
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
|
||||
@@ -420,14 +503,19 @@ def overview_map(recs, label, *, wide=False, scope=""):
|
||||
</div>
|
||||
<figcaption class="mapfig__caption">
|
||||
<ul class="legend" aria-label="Legend">
|
||||
<li>{common.SWATCH_LINE}Official trail</li>
|
||||
<li>{common.SWATCH_ROUTE}Route</li>
|
||||
{legend}
|
||||
</ul>
|
||||
<p>{n} track{"s" if n != 1 else ""}, simplified for display. Select one for its name. Each trail’s page names its source, credit and licence. Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.</p>
|
||||
<p>{" ".join(sentences)}</p>
|
||||
</figcaption>
|
||||
</figure>""")
|
||||
|
||||
|
||||
def has_overview_map(recs, scope=""):
|
||||
"""True when overview_map would draw a map of these trails (needs the map library)."""
|
||||
n = len(drawable_ids(recs))
|
||||
return n > 0 and (scope == "all" or n >= MAP_MIN)
|
||||
|
||||
|
||||
def lists_row(records):
|
||||
"""The ready-made lists, as a row of links with their counts. The terrain lists are
|
||||
on /lists/; here the Terrain filter does the same work."""
|
||||
|
||||
+4
-4
@@ -123,7 +123,7 @@ def region_page(slug, records, site):
|
||||
</div>"""
|
||||
title = info["name"]
|
||||
desc = f"{_plural(len(recs))} in {info['name']}, {country}: length, time and where to get the GPX."
|
||||
return title, desc, Markup(body), n_gpx >= home.MAP_MIN
|
||||
return title, desc, Markup(body), home.has_overview_map(recs)
|
||||
|
||||
|
||||
def route_guides(rec):
|
||||
@@ -172,7 +172,7 @@ def routes_page(records, site, repo_root=None):
|
||||
{home.results(groups=groups, routes_list=True)}
|
||||
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
|
||||
</div>"""
|
||||
return "Routes", f"{_plural(len(routes), 'route')} in the United States and Canada, by author, with their guides.", Markup(body), n_gpx >= home.MAP_MIN
|
||||
return "Routes", f"{_plural(len(routes), 'route')} in the United States and Canada, by author, with their guides.", Markup(body), home.has_overview_map(routes)
|
||||
|
||||
|
||||
def list_page(lst, recs, total, site):
|
||||
@@ -192,11 +192,11 @@ def list_page(lst, recs, total, site):
|
||||
</div></div>
|
||||
<div class="container section">
|
||||
{home.overview_map(recs, f"Map of the trails in the list {lst.title}")}
|
||||
{home.results(recs)}
|
||||
{home.results(recs, default_sort=lst.sort)}
|
||||
<p class="finder__foot">{rule}</p>
|
||||
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
|
||||
</div>"""
|
||||
return lst.title, f"{lst.title}: {lst.blurb}", Markup(body), n_gpx >= home.MAP_MIN
|
||||
return lst.title, f"{lst.title}: {lst.blurb}", Markup(body), home.has_overview_map(recs)
|
||||
|
||||
|
||||
def lists_index_page(records, site):
|
||||
|
||||
+76
-5
@@ -366,8 +366,9 @@ ROUTE_NO_GPX = {
|
||||
}
|
||||
|
||||
|
||||
def empty_frame(rec):
|
||||
"""The map frame of a trail with no GPX here: why, and where to get one."""
|
||||
def _no_gpx_parts(rec):
|
||||
"""(title, status, reason, rule, actions_html): why there is no GPX here
|
||||
and where to get one, for the empty frame and the sketch map alike."""
|
||||
src = rec["source"]
|
||||
reason = src.get("line_absent_reason", "")
|
||||
actions = []
|
||||
@@ -404,6 +405,12 @@ def empty_frame(rec):
|
||||
reason = Markup(f'{esc(lead)}</p><p class="note"><strong>Why there is none here:</strong> '
|
||||
f'{common.rich(reason)}')
|
||||
actions_html = f'<p class="cluster">{"".join(actions)}</p>' if actions else ""
|
||||
return title, status, reason, rule, actions_html
|
||||
|
||||
|
||||
def empty_frame(rec):
|
||||
"""The map frame of a trail with no GPX here and no known start or end point."""
|
||||
title, status, reason, rule, actions_html = _no_gpx_parts(rec)
|
||||
return f"""<figure class="mapfig mapfig--empty detail__map" id="track" aria-labelledby="noline-title">
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true">No GPX here</span>
|
||||
@@ -422,6 +429,68 @@ def empty_frame(rec):
|
||||
</figure>"""
|
||||
|
||||
|
||||
def sketch_figure(rec):
|
||||
"""A real map for a trail with no track but a known start or end: a dotted
|
||||
straight line between the two, or one ring. It says plainly that the line only
|
||||
joins the start and the end, and keeps the words about where to get a track."""
|
||||
points = hike.sketch_points(rec)
|
||||
box = hike.sketch_bbox(points, pad=True)
|
||||
bbox_attr = f' data-bbox="{",".join(str(v) for v in box)}"' if box else ""
|
||||
route = common.is_route(rec)
|
||||
h = hike.table(rec)
|
||||
start = h.get("start") if isinstance(h.get("start"), str) else ""
|
||||
end = h.get("end") if isinstance(h.get("end"), str) else ""
|
||||
start, end = start.strip(), end.strip()
|
||||
if len(points) == 2:
|
||||
if start and end:
|
||||
where = (f"The dotted line runs straight from {esc(start)} to {esc(end)}. "
|
||||
"It only joins the start and the end; that is not the trail’s path.")
|
||||
elif start:
|
||||
where = (f"The dotted line runs straight from {esc(start)} to where it ends. "
|
||||
"It only joins the start and the end; that is not the trail’s path.")
|
||||
else:
|
||||
where = ("The dotted line runs straight between its start and its end. "
|
||||
"It only joins the two; that is not the trail’s path.")
|
||||
legend_text = "No GPX here: start and end only"
|
||||
else:
|
||||
if hike.sketch_end(rec) == "end":
|
||||
where = (f"The ring marks {esc(end)}, where it ends. " if end else "The ring marks where it ends. ")
|
||||
where += "No position is on file for the start, so no line is drawn."
|
||||
legend_text = "No GPX here: end only"
|
||||
elif h.get("shape") == "loop":
|
||||
where = (f"The ring marks {esc(start)}, where the loop starts and ends. " if start
|
||||
else "The ring marks where the loop starts and ends. ")
|
||||
where += "It shows where the trail is, not its path."
|
||||
legend_text = "No GPX here: start only"
|
||||
else:
|
||||
where = (f"The ring marks {esc(start)}, where it starts. " if start else "The ring marks where it starts. ")
|
||||
where += "No position is on file for the end, so no line is drawn."
|
||||
legend_text = "No GPX here: start only"
|
||||
_title, status, reason, rule, actions_html = _no_gpx_parts(rec)
|
||||
reason_html = reason if isinstance(reason, Markup) else common.rich(reason)
|
||||
return f"""<figure class="mapfig mapfig--detail detail__map" id="track" data-map="sketch" data-src="/trails/{esc(rec["id"])}/sketch.json" data-route="{"yes" if route else "no"}"{bbox_attr}>
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
|
||||
<div class="map" role="region" aria-label="Map showing the start and end of the {esc(rec["name"])}; no GPX here">
|
||||
<div class="map__fallback"></div>
|
||||
<div class="map__canvas"></div>
|
||||
<p class="map__status" role="status">The map needs JavaScript. The ends of the trail are named below it.</p>
|
||||
</div>
|
||||
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
|
||||
</div>
|
||||
<figcaption class="mapfig__caption mapfig__caption--sketch">
|
||||
<ul class="legend" aria-label="Legend"><li>{common.SWATCH_SKETCH}{esc(legend_text)}</li></ul>
|
||||
<div class="sketch-note">
|
||||
<p><strong>No GPX here.</strong> {where}</p>
|
||||
<p>{reason_html}</p>
|
||||
<p class="note">{esc(rule)}</p>
|
||||
{actions_html}
|
||||
<p>Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.</p>
|
||||
</div>
|
||||
</figcaption>
|
||||
</figure>"""
|
||||
|
||||
|
||||
# Aside: downloads, guides, links --------------------------------------------
|
||||
|
||||
def ordered_downloads(items):
|
||||
@@ -1081,15 +1150,17 @@ def onward(rec, records):
|
||||
def render(rec, site, records=None):
|
||||
"""Return (title, description, body HTML, needs_map) for one trail.
|
||||
records: every trail, for the ways onward at the foot (left out when None)."""
|
||||
has_map = common.has_line(rec)
|
||||
has_track = common.has_line(rec)
|
||||
sketch = hike.sketch_points(rec) if not has_track else []
|
||||
has_map = has_track or bool(sketch)
|
||||
aside = downloads_panel(rec) + guides_panel(rec)
|
||||
aside_html = (f'<aside class="detail__aside" aria-label="{"Downloads" if has_map else "Where to get the route"}">'
|
||||
aside_html = (f'<aside class="detail__aside" aria-label="{"Downloads" if has_track else "Where to get the route"}">'
|
||||
f'{aside}</aside>') if aside else ""
|
||||
profile = elevation_figure(rec)
|
||||
body = f"""{page_head(rec)}
|
||||
<div class="container detail{"" if aside else " detail--no-aside"}{"" if has_map else " detail--no-map"}{" detail--with-profile" if profile else ""}">
|
||||
{glance(rec)}
|
||||
{map_figure(rec) if has_map else empty_frame(rec)}
|
||||
{map_figure(rec) if has_track else sketch_figure(rec) if sketch else empty_frame(rec)}
|
||||
{profile}
|
||||
{aside_html}
|
||||
</div>
|
||||
|
||||
@@ -238,13 +238,13 @@ class CatalogueTest(unittest.TestCase):
|
||||
row_none = home.entry(rec_with(None))
|
||||
self.assertIn('data-climb=""', row_none)
|
||||
self.assertNotIn("<dt>Climb</dt>", row_none)
|
||||
self.assertIn('<option value="climb">Most climb first</option>', home.SORT_SELECT)
|
||||
self.assertIn('<option value="climb-desc">Climb, most first</option>', home.SORT_SELECT)
|
||||
self.assertIn('<option value="climb-asc">Climb, least first</option>', home.SORT_SELECT)
|
||||
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
|
||||
js = f.read()
|
||||
self.assertIn("key === 'climb'", js)
|
||||
# a trail with no computed climb sorts last, not first
|
||||
self.assertIn("a.dataset.climb === '' ? -1", js)
|
||||
self.assertIn("return bc - ac", js)
|
||||
self.assertIn("'climb-desc'", js)
|
||||
# a trail with no computed climb sorts last in both climb orders
|
||||
self.assertIn("ac === null ? 1 : -1", js)
|
||||
|
||||
|
||||
class RoutesListTest(unittest.TestCase):
|
||||
|
||||
@@ -133,15 +133,17 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
for rel in ("index.html", "regions/us-co/index.html", "routes/index.html",
|
||||
"lists/national-scenic-trails/index.html"):
|
||||
doc = read_out(rel)
|
||||
results = doc[doc.index('<div class="results">'):]
|
||||
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"'):
|
||||
'name="units-list"', '<ul class="key"', "Sort by", 'data-sort-select'):
|
||||
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)
|
||||
for name in ("Length", "Time", "GPX"):
|
||||
self.assertIn(f"<span>{name}", scale, rel)
|
||||
for name in ("Length", "Time", "GPX", "Climb"):
|
||||
self.assertIn(name, scale, rel)
|
||||
for col in ("name", "length", "time", "climb"):
|
||||
self.assertIn(f'data-sort-col="{col}"', scale, rel)
|
||||
self.assertNotIn('class="route-item"', read_out("routes/index.html"))
|
||||
|
||||
def test_routes_page_rows_carry_their_guides(self):
|
||||
|
||||
@@ -296,7 +296,9 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
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>")]
|
||||
# The hatched frame, or the map of a trail drawn from its start and end.
|
||||
start = re.search(r'<figure class="mapfig (?:mapfig--empty|[^"]*"[^>]* data-map="sketch")', page).start()
|
||||
frame = page[start:page.index("</figure>", start)]
|
||||
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"])
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
"""Tests for sorting every list of trails, and for sketching trails with no
|
||||
track on maps from their start (and end) points.
|
||||
|
||||
Sort parity: the Python order (facets.sort_records) is compared with a Python
|
||||
re-implementation of the app.js comparator over the rendered rows' data-*
|
||||
attributes, for each of the eight keys, so the check needs no browser.
|
||||
"""
|
||||
import copy
|
||||
import html
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
from functools import cmp_to_key
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, WEB)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import build # noqa: E402
|
||||
from olt import browse, docs, facets, hike, home, records, trail # noqa: E402
|
||||
from test_hike import GH, fake # noqa: E402
|
||||
|
||||
|
||||
def make(id_, name, km=100, days=None, climb=None, coverage=1.0, **kw):
|
||||
rec = fake(1, km=km, **kw)
|
||||
rec["id"], rec["name"] = id_, name
|
||||
if days is not None:
|
||||
rec["hike"] = dict(rec.get("hike") or {}, days=days)
|
||||
if climb is not None:
|
||||
rec["derived"]["elevation"] = {"ascent_m": climb, "coverage": coverage}
|
||||
return rec
|
||||
|
||||
|
||||
def ids(recs):
|
||||
return [r["id"] for r in recs]
|
||||
|
||||
|
||||
def row_data(rec):
|
||||
"""The data-* values of a rendered row, as the script reads them."""
|
||||
row = home.entry(rec)
|
||||
attrs = dict(re.findall(r'data-(\w+)="([^"]*)"', row.split("\n", 1)[0]))
|
||||
return {k: html.unescape(v) for k, v in attrs.items()}
|
||||
|
||||
|
||||
def _cmp(a, b):
|
||||
return (a > b) - (a < b)
|
||||
|
||||
|
||||
def js_compare(x, y, key):
|
||||
"""compareEntries in app.js, restated over parsed data-* strings."""
|
||||
if key == "name":
|
||||
return _cmp(x["name"], y["name"])
|
||||
if key == "name-desc":
|
||||
return _cmp(y["name"], x["name"])
|
||||
if key.startswith("climb"):
|
||||
xc = None if x["climb"] == "" else float(x["climb"])
|
||||
yc = None if y["climb"] == "" else float(y["climb"])
|
||||
if xc is None or yc is None:
|
||||
if xc is None and yc is None:
|
||||
return _cmp(x["name"], y["name"])
|
||||
return 1 if xc is None else -1
|
||||
return (_cmp(yc, xc) if key == "climb-desc" else _cmp(xc, yc)) or _cmp(x["name"], y["name"])
|
||||
field = "km" if key.startswith("length") else "days"
|
||||
order = _cmp(float(y[field]), float(x[field])) if key.endswith("-desc") else _cmp(float(x[field]), float(y[field]))
|
||||
return order or _cmp(x["name"], y["name"])
|
||||
|
||||
|
||||
FIXTURES = [
|
||||
make("b-trail", "B Trail", km=300, days=[10, 20], climb=5000),
|
||||
make("a-trail", "The A Trail", km=100, days=[5, 20], climb=9000),
|
||||
make("c-trail", "C Trail", km=300, days=[3, 8]), # no climb
|
||||
make("d-trail", "D Trail", km=50, days=[30, 40], climb=1000, coverage=0.5), # climb hidden
|
||||
make("e-trail", "E Trail", km=900, days=[60, 90], climb=9000),
|
||||
]
|
||||
|
||||
|
||||
class SortKeysTest(unittest.TestCase):
|
||||
def test_options_in_order_and_wording(self):
|
||||
self.assertEqual([label for _, label in facets.SORTS], [
|
||||
"Name, A to Z", "Name, Z to A", "Length, longest first", "Length, shortest first",
|
||||
"Time, quickest first", "Time, slowest first", "Climb, most first", "Climb, least first"])
|
||||
select = home.sort_select("length-asc")
|
||||
self.assertIn('<span class="results-sort__label">Sort by</span>', select)
|
||||
self.assertIn('<option value="length-asc" selected>Length, shortest first</option>', select)
|
||||
self.assertEqual([m for m in re.findall(r'<option value="([^"]+)"', select)],
|
||||
[k for k, _ in facets.SORTS])
|
||||
|
||||
def test_old_address_keys_still_work(self):
|
||||
for old, new in [("long", "length-desc"), ("short", "length-asc"),
|
||||
("quick", "time-asc"), ("climb", "climb-desc"), ("name", "name")]:
|
||||
self.assertEqual(facets.normalize_sort(old), new, old)
|
||||
self.assertEqual(facets.normalize_sort("bogus", "time-asc"), "time-asc")
|
||||
self.assertEqual(facets.normalize_sort(None), "name")
|
||||
|
||||
def test_each_order(self):
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, "name")),
|
||||
["a-trail", "b-trail", "c-trail", "d-trail", "e-trail"])
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, "name-desc")),
|
||||
["e-trail", "d-trail", "c-trail", "b-trail", "a-trail"])
|
||||
# 300 km tie falls back to name
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, "length-desc")),
|
||||
["e-trail", "b-trail", "c-trail", "a-trail", "d-trail"])
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, "length-asc")),
|
||||
["d-trail", "a-trail", "b-trail", "c-trail", "e-trail"])
|
||||
# 20-day tie falls back to name
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, "time-asc")),
|
||||
["c-trail", "a-trail", "b-trail", "d-trail", "e-trail"])
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, "time-desc")),
|
||||
["e-trail", "d-trail", "a-trail", "b-trail", "c-trail"])
|
||||
# no climb (or a hidden one) goes last in both climb orders, by name
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, "climb-desc")),
|
||||
["a-trail", "e-trail", "b-trail", "c-trail", "d-trail"])
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, "climb-asc")),
|
||||
["b-trail", "a-trail", "e-trail", "c-trail", "d-trail"])
|
||||
|
||||
def test_hidden_climb_is_empty_in_the_row(self):
|
||||
data = row_data(FIXTURES[3]) # coverage 0.5: the row hides its climb
|
||||
self.assertEqual(data["climb"], "")
|
||||
self.assertNotIn("<dt>Climb</dt>", home.entry(FIXTURES[3]))
|
||||
|
||||
def test_python_order_matches_the_script_over_row_data(self):
|
||||
rows = [row_data(r) for r in FIXTURES]
|
||||
for key, _ in facets.SORTS:
|
||||
script_order = [d["id"] for d in sorted(rows, key=cmp_to_key(lambda a, b, k=key: js_compare(a, b, k)))]
|
||||
self.assertEqual(ids(facets.sort_records(FIXTURES, key)), script_order, key)
|
||||
|
||||
def test_real_records_sort_by_name(self):
|
||||
recs = records.load_records()
|
||||
names = [facets.sort_name(r) for r in facets.sort_records(recs, "name")]
|
||||
self.assertEqual(names, sorted(names))
|
||||
|
||||
|
||||
class ListDefaultsTest(unittest.TestCase):
|
||||
def test_only_four_lists_open_in_another_order(self):
|
||||
special = {lst.key: lst.sort for lst in browse.LISTS if lst.sort != "name"}
|
||||
self.assertEqual(special, {"longest": "length-desc", "under-100-km": "length-asc",
|
||||
"a-week-or-less": "time-asc", "one-to-two-weeks": "time-asc"})
|
||||
for lst in browse.LISTS:
|
||||
self.assertIn(lst.sort, facets.SORT_LABEL, lst.key)
|
||||
self.assertFalse(hasattr(lst, "order"), lst.key)
|
||||
|
||||
def test_members_come_in_the_list_order(self):
|
||||
recs = [make("short", "Short", km=3000), make("long", "Long", km=5000), make("mid", "Mid", km=100)]
|
||||
self.assertEqual(ids(browse.members(browse.by_key("longest"), recs)), ["long", "short"])
|
||||
self.assertEqual(ids(browse.members(browse.by_key("under-100-km"),
|
||||
[make("a", "A", km=90), make("b", "B", km=10)])), ["b", "a"])
|
||||
|
||||
|
||||
class ResultsHtmlTest(unittest.TestCase):
|
||||
def test_every_list_has_the_sort_control_in_its_default_order(self):
|
||||
doc = str(home.results(FIXTURES, default_sort="length-desc"))
|
||||
self.assertIn("Sort by", doc)
|
||||
self.assertIn('data-default-sort="length-desc"', doc)
|
||||
self.assertIn('<option value="length-desc" selected>', doc)
|
||||
self.assertEqual(re.findall(r'data-id="([^"]+)"', doc),
|
||||
ids(facets.sort_records(FIXTURES, "length-desc")))
|
||||
self.assertIn('data-sort-status', doc)
|
||||
|
||||
def test_column_heads_are_sort_buttons_that_agree(self):
|
||||
head = home.list_head("time-desc")
|
||||
self.assertIn('aria-hidden="true"', head)
|
||||
for col in ("name", "length", "time", "climb"):
|
||||
self.assertIn(f'data-sort-col="{col}"', head)
|
||||
self.assertNotIn('data-sort-col="gpx"', head)
|
||||
self.assertIn("GPX", head)
|
||||
# the active column is marked, the rest show the two-way mark
|
||||
self.assertIn('class="list-head__sort is-active" data-sort-col="time"', head)
|
||||
self.assertIn("↓", head)
|
||||
self.assertIn("↕", head)
|
||||
# buttons stay out of the tab order: the select is the one control
|
||||
self.assertEqual(head.count('tabindex="-1"'), 4)
|
||||
|
||||
def test_grouped_lists_sort_within_each_group(self):
|
||||
groups = [("By B", [FIXTURES[0], FIXTURES[1]], None),
|
||||
("By A", [FIXTURES[4], FIXTURES[2]], None)]
|
||||
doc = str(home.results(groups=groups, default_sort="length-asc"))
|
||||
self.assertEqual(re.findall(r'data-id="([^"]+)"', doc),
|
||||
["a-trail", "b-trail", "c-trail", "e-trail"])
|
||||
self.assertLess(doc.index("By B"), doc.index("By A")) # group order kept
|
||||
|
||||
|
||||
def sketch_rec(id_="sk", name="Sketch Trail", start=(-110.0, 40.0), end=(-100.0, 45.0), **kw):
|
||||
hike_table = {"start": "Start Town", "shape": "point-to-point"}
|
||||
if start is not None:
|
||||
hike_table["start_lonlat"] = list(start)
|
||||
if end is not None:
|
||||
hike_table["end"] = "End Town"
|
||||
hike_table["end_lonlat"] = list(end)
|
||||
rec = make(id_, name, hike=hike_table, **kw)
|
||||
return rec
|
||||
|
||||
|
||||
class SketchPointsTest(unittest.TestCase):
|
||||
def test_points_are_read_and_checked(self):
|
||||
self.assertEqual(hike.sketch_points(sketch_rec()), [[-110.0, 40.0], [-100.0, 45.0]])
|
||||
self.assertEqual(hike.sketch_points(sketch_rec(end=None)), [[-110.0, 40.0]])
|
||||
self.assertEqual(hike.sketch_points(sketch_rec(start=None)), [[-100.0, 45.0]])
|
||||
self.assertEqual(hike.sketch_end(sketch_rec(start=None)), "end")
|
||||
self.assertEqual(hike.sketch_end(sketch_rec(end=None)), "start")
|
||||
self.assertEqual(hike.sketch_end(sketch_rec()), "")
|
||||
bad = sketch_rec(end=None)
|
||||
bad["hike"]["start_lonlat"] = [999, 40]
|
||||
self.assertEqual(hike.sketch_points(bad), [])
|
||||
bad["hike"]["start_lonlat"] = "not a place"
|
||||
self.assertEqual(hike.sketch_points(bad), [])
|
||||
|
||||
def test_a_track_suppresses_the_sketch(self):
|
||||
rec = sketch_rec()
|
||||
rec["derived"]["has_line"] = True
|
||||
rec["derived"]["files"] = {"line": "sk/line.geojson"}
|
||||
self.assertEqual(hike.sketch_points(rec), [])
|
||||
|
||||
def test_sketch_is_never_a_track(self):
|
||||
rec = sketch_rec()
|
||||
self.assertEqual(facets.gpx(rec), "elsewhere")
|
||||
self.assertFalse(facets.gpx_here(rec))
|
||||
self.assertEqual(build.trail_outputs(rec["id"], {}, rec), ["sketch.json"])
|
||||
self.assertEqual(rec["derived"]["downloads"], [])
|
||||
self.assertIsNone(facets.row_climb_m(rec))
|
||||
|
||||
def test_sketch_features(self):
|
||||
feats = build.sketch_features(sketch_rec())
|
||||
self.assertEqual([f["geometry"]["type"] for f in feats], ["LineString", "MultiPoint"])
|
||||
for f in feats:
|
||||
self.assertIs(f["properties"]["sketch"], True)
|
||||
self.assertEqual(f["properties"]["id"], "sk")
|
||||
self.assertEqual(f["properties"]["name"], "Sketch Trail")
|
||||
one = build.sketch_features(sketch_rec(end=None))
|
||||
self.assertEqual([f["geometry"]["type"] for f in one], ["MultiPoint"])
|
||||
self.assertEqual(one[0]["geometry"]["coordinates"], [[-110.0, 40.0]])
|
||||
self.assertEqual(build.sketch_features(make("plain", "Plain")), [])
|
||||
|
||||
def test_overview_includes_sketches_only(self):
|
||||
fc = build.overview_geojson([sketch_rec(), make("plain", "Plain")], "/nonexistent")
|
||||
self.assertEqual(sorted({f["properties"]["id"] for f in fc["features"]}), ["sk"])
|
||||
|
||||
|
||||
class SketchMapTest(unittest.TestCase):
|
||||
def test_sketches_count_toward_the_map_minimum(self):
|
||||
recs = [sketch_rec(f"s{i}", f"S{i}") for i in range(3)]
|
||||
doc = str(home.overview_map(recs, "Map"))
|
||||
self.assertIn('data-map="overview"', doc)
|
||||
self.assertIn("No GPX here: start and end only", doc)
|
||||
self.assertIn("dotted straight line between their start and end", doc)
|
||||
self.assertIn("That is not the trail’s path.", doc)
|
||||
for i in range(3):
|
||||
self.assertIn(f"s{i}", doc)
|
||||
self.assertTrue(home.has_overview_map(recs))
|
||||
self.assertIn("-110.0000", home.overview_bbox(recs))
|
||||
|
||||
def test_too_few_drawable_is_a_note_that_stays_true(self):
|
||||
doc = str(home.overview_map([sketch_rec()], "Map"))
|
||||
self.assertNotIn('data-map="overview"', doc)
|
||||
self.assertIn("a GPX here or a known start or end", doc)
|
||||
doc = str(home.overview_map([make("plain", "Plain")], "Map"))
|
||||
self.assertIn("or a known start or end, so there is nothing to draw", doc)
|
||||
self.assertFalse(home.has_overview_map([sketch_rec()]))
|
||||
|
||||
def test_no_sketch_no_legend_entry(self):
|
||||
recs = []
|
||||
for i in range(3):
|
||||
rec = make(f"t{i}", f"T{i}")
|
||||
rec["derived"]["files"] = {"line": f"t{i}/line.geojson"}
|
||||
rec["derived"]["has_line"] = True
|
||||
recs.append(rec)
|
||||
doc = str(home.overview_map(recs, "Map"))
|
||||
self.assertIn("3 tracks, simplified for display.", doc)
|
||||
self.assertNotIn("start and end only", doc)
|
||||
|
||||
def test_trail_page_shows_a_sketch_map(self):
|
||||
_t, _d, body, needs_map = trail.render(sketch_rec(), GH)
|
||||
self.assertTrue(needs_map)
|
||||
self.assertIn('data-map="sketch"', body)
|
||||
self.assertIn("/trails/sk/sketch.json", body)
|
||||
self.assertIn("Start Town", body)
|
||||
self.assertIn("End Town", body)
|
||||
self.assertIn("not the trail’s path", body)
|
||||
self.assertIn("No GPX here", body)
|
||||
self.assertNotIn("map--empty", body)
|
||||
|
||||
def test_trail_page_with_only_a_start_shows_a_ring(self):
|
||||
_t, _d, body, needs_map = trail.render(sketch_rec(end=None), GH)
|
||||
self.assertTrue(needs_map)
|
||||
self.assertIn("The ring marks Start Town", body)
|
||||
|
||||
def test_trail_page_without_a_point_keeps_the_empty_frame(self):
|
||||
_t, _d, body, needs_map = trail.render(make("plain", "Plain Trail"), GH)
|
||||
self.assertFalse(needs_map)
|
||||
self.assertIn("map--empty", body)
|
||||
self.assertNotIn("sketch.json", body)
|
||||
|
||||
|
||||
class ScriptAndDocsTest(unittest.TestCase):
|
||||
def test_script_has_the_dotted_sketch_and_the_sort_state(self):
|
||||
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
|
||||
js = f.read()
|
||||
for part in ("dash: [0, 2]", "olt-sketch-points", "No GPX here. The dotted line only joins",
|
||||
"normalizeSortKey", "replaceState", "data-sort-col", "'long': 'length-desc'",
|
||||
"fallback__ring", "fallback__line--sketch"):
|
||||
self.assertIn(part, js, part)
|
||||
|
||||
def test_data_page_describes_sketches(self):
|
||||
text = " ".join(what for _, what, _ in docs.BULK_FILES)
|
||||
self.assertIn("sketch", text.lower())
|
||||
self.assertIn("not a track", text.lower())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user