From 51baaa401e0e694ab05ffd82f9645cdb7b535b88 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 14 Nov 2026 17:30:12 -0700 Subject: [PATCH] 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 --- web/assets/app.js | 332 +++++++++++++++++++++++++++++------- web/assets/style.css | 35 +++- web/build.py | 43 ++++- web/olt/browse.py | 19 +-- web/olt/common.py | 2 + web/olt/docs.py | 5 +- web/olt/facets.py | 86 +++++++++- web/olt/hike.py | 69 ++++++++ web/olt/home.py | 184 ++++++++++++++------ web/olt/regions.py | 8 +- web/olt/trail.py | 81 ++++++++- web/tests/test_elevation.py | 10 +- web/tests/test_extra.py | 10 +- web/tests/test_pages.py | 4 +- web/tests/test_sorting.py | 310 +++++++++++++++++++++++++++++++++ 15 files changed, 1049 insertions(+), 149 deletions(-) create mode 100644 web/tests/test_sorting.py diff --git a/web/assets/app.js b/web/assets/app.js index 60f4cf9..3e57e08 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -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= 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
(About this data) opens it, so the target is shown rather than hidden. */ diff --git a/web/assets/style.css b/web/assets/style.css index 7d826c9..a82f9b2 100644 --- a/web/assets/style.css +++ b/web/assets/style.css @@ -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%; } diff --git a/web/build.py b/web/build.py index 28bbe43..b14e56d 100644 --- a/web/build.py +++ b/web/build.py @@ -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// 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 diff --git a/web/olt/browse.py b/web/olt/browse.py index 2061fb9..95a1cf5 100644 --- a/web/olt/browse.py +++ b/web/olt/browse.py @@ -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): diff --git a/web/olt/common.py b/web/olt/common.py index 769b15b..6a53b2d 100644 --- a/web/olt/common.py +++ b/web/olt/common.py @@ -180,6 +180,8 @@ SWATCH_LINE = Markup('') SWATCH_ALT = Markup('') SWATCH_NONE = Markup('') +# A trail with no track, sketched from its start (and end) points only. +SWATCH_SKETCH = Markup('') ICON_DOWNLOAD = Markup('') diff --git a/web/olt/docs.py b/web/olt/docs.py index e9df902..7ced7ab 100644 --- a/web/olt/docs.py +++ b/web/olt/docs.py @@ -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 /, " "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 /, " @@ -432,6 +434,7 @@ def data_page(records, site, repo_root, out_dir): ("-alternates.geojson / .gpx", "Alternate and connector tracks, where the source serves them separately."), ("-.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."), diff --git a/web/olt/facets.py b/web/olt/facets.py index ad9a8f0..5933000 100644 --- a/web/olt/facets.py +++ b/web/olt/facets.py @@ -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))) diff --git a/web/olt/hike.py b/web/olt/hike.py index 56bd514..98e7aaf 100644 --- a/web/olt/hike.py +++ b/web/olt/hike.py @@ -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] diff --git a/web/olt/home.py b/web/olt/home.py index 51dbf32..d6e132e 100644 --- a/web/olt/home.py +++ b/web/olt/home.py @@ -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

{esc(desc)}

' if desc else "" time_html = esc(facets.time_text(rec)) + (' estimate' if est else "") - climb_html = (f'\n
Climb
{words.elevation(elev["ascent_m"], "stack")}' - f'computed
') if elev else "" + climb_html = (f'\n
Climb
{words.elevation(climb_m, "stack")}' + f'computed
') if climb_m is not None else "" return f"""
  • {common.plate(rec)}
    {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'{extra}') + + +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'{km:,}{unit}' f'{words.fmt_int(words.km_to_mi(km))}{mi_unit}') + scale = f'{"".join(ticks)}' return f"""""" @@ -322,15 +349,22 @@ UNITS_TOGGLE = """
    """ -SORT_SELECT = """""" + + """ + + +SORT_SELECT = sort_select() def key(official=True): @@ -342,16 +376,24 @@ def key(official=True): """ -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'

    ' f'{total} of {total} {noun}

    ') - tools = SORT_SELECT + "\n " + UNITS_TOGGLE empty = """ """ else: count = f'

    {total} {noun}

    ' - tools = UNITS_TOGGLE empty = "" - return Markup(f"""
    + tools = sort_select(default_sort) + "\n " + UNITS_TOGGLE + return Markup(f"""
    {count}
    @@ -386,28 +427,70 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False):
    {key(official=not only_routes)} - {list_head()}{lists}{empty} + {list_head(default_sort)}{lists}{empty}
    """) -# 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('

    None of these trails has a GPX here, so there is no track to draw. ' - 'Each trail’s page says where to get one.

    ') + return Markup('

    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.

    ') if len(ids) < MAP_MIN and scope != "all": names = words.join_names(f'{common.name(r)}' for r in recs if r["id"] in ids) - return Markup(f'

    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.

    ') + return Markup(f'

    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.

    ') 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"
  • {common.SWATCH_LINE}Official trail
  • ") + if scope == "all" or any(common.is_route(r) for r in drawn): + legend.append(f"
  • {common.SWATCH_ROUTE}Route
  • ") + if sketches: + legend.append(f"
  • {common.SWATCH_SKETCH}No GPX here: start and end only
  • ") + 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"""
    @@ -420,14 +503,19 @@ def overview_map(recs, label, *, wide=False, scope=""):
      -
    • {common.SWATCH_LINE}Official trail
    • -
    • {common.SWATCH_ROUTE}Route
    • + {legend}
    -

    {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.

    +

    {" ".join(sentences)}

    """) +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.""" diff --git a/web/olt/regions.py b/web/olt/regions.py index d62639a..ce76aeb 100644 --- a/web/olt/regions.py +++ b/web/olt/regions.py @@ -123,7 +123,7 @@ def region_page(slug, records, site): """ 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)} """ - 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):
    {home.overview_map(recs, f"Map of the trails in the list {lst.title}")} - {home.results(recs)} + {home.results(recs, default_sort=lst.sort)}

    {rule}

    """ - 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): diff --git a/web/olt/trail.py b/web/olt/trail.py index a6687a0..8e1c18e 100644 --- a/web/olt/trail.py +++ b/web/olt/trail.py @@ -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)}

    Why there is none here: ' f'{common.rich(reason)}') actions_html = f'

    {"".join(actions)}

    ' 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"""
    @@ -422,6 +429,68 @@ def empty_frame(rec):
    """ +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"""
    +
    + +
    +
    +
    +

    The map needs JavaScript. The ends of the trail are named below it.

    +
    + +
    +
    +
    • {common.SWATCH_SKETCH}{esc(legend_text)}
    +
    +

    No GPX here. {where}

    +

    {reason_html}

    +

    {esc(rule)}

    + {actions_html} +

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

    +
    +
    +
    """ + + # 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'