diff --git a/web/assets/app.js b/web/assets/app.js index ef03616..60f4cf9 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -7,7 +7,7 @@ 3. Trail finder (home page): search, filters, sort, URL query state, map/list highlight 4. Copy-credit buttons - Every page works without this script: the list holds every record and each map + Every page works without this script: the list holds every trail and each map frame keeps its size, border and caption. */ (function () { 'use strict'; @@ -492,7 +492,7 @@ a.href = '/trails/' + encodeURIComponent(p.id) + '/'; a.textContent = p.name; var meta = document.createElement('p'); - meta.textContent = lengthText(Number(p.length_km)) + (p.kind === 'route' ? ' · person-defined route' : ''); + meta.textContent = lengthText(Number(p.length_km)) + (p.kind === 'route' ? ' · Route' : ''); box.appendChild(a); box.appendChild(meta); popup.setLngLat(e.lngLat).setDOMContent(box).addTo(map); @@ -527,6 +527,14 @@ entry.visibleIds = ids; var set = {}; ids.forEach(function (id) { set[id] = true; }); + /* Without the base map, the plain drawing is redrawn on the tracks still + shown, so the map shows what the filters leave at a useful scale. */ + if (!entry.ready && entry.fc && entry.kind === 'overview') { + var sub = entry.fc.features.filter(function (f) { return set[(f.properties || {}).id]; }); + var whole = sub.length === entry.fc.features.length; + if (sub.length) drawFallback(entry.fallback, whole ? entry.fc : { type: 'FeatureCollection', features: sub }, + whole && entry.fullBounds ? entry.fullBounds : bboxOf({ features: sub }), false); + } entry.fallback.querySelectorAll('[data-id]').forEach(function (path) { path.style.display = set[path.getAttribute('data-id')] ? '' : 'none'; }); @@ -548,7 +556,17 @@ if (window.maplibregl || document.readyState === 'complete') startMaps(); else window.addEventListener('load', startMaps); - /* 3. Trail finder (home page) ------------------------------------------------ */ + /* 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 + as data-* attributes (olt/home.py entry()). A filter on a facet that a + trail has no value for leaves that trail out, and the note under the + filter (data-missing) says how many trails have no value on file. */ + + var MULTI = ['time', 'terrain', 'walking', 'shape', 'gpx']; + var MORE = ['walking', 'shape', 'gpx']; + /* Addresses from before the site had these filters still work. */ + var OLD_POLICY = { open: 'free', sold: 'sold', withheld: 'unpublished', unclear: 'elsewhere' }; function initFinder(form) { var list = document.getElementById('entries'); @@ -584,7 +602,18 @@ } function hasOption(select, value) { - return Array.prototype.some.call(select.options, function (o) { return o.value === value; }); + return !!select && Array.prototype.some.call(select.options, function (o) { return o.value === value; }); + } + + function boxes(name) { + return Array.prototype.slice.call(form.querySelectorAll('input[type="checkbox"][name="' + name + '"]')); + } + function checked(name) { + return boxes(name).filter(function (b) { return b.checked; }).map(function (b) { return b.value; }); + } + function radio(name) { + var r = form.querySelector('input[name="' + name + '"]:checked'); + return r ? r.value : ''; } function read() { @@ -592,39 +621,36 @@ var max = Number(el.max.value) || Infinity; var swapped = min > max; if (swapped) { var keep = min; min = max; max = keep; } - return { + var s = { q: el.q.value.trim(), words: el.q.value.trim().toLowerCase().split(/\s+/).filter(Boolean), - country: el.country.value, - region: el.region.value, + where: el.where.value, min: min, max: max, swapped: swapped, - designated: el.designated.checked, - route: el.route.checked, - line: el.line.checked, - policy: el.policy.value, - tier: el.tier.value + month: el.month ? el.month.value : '', + kind: radio('kind') }; + MULTI.forEach(function (name) { s[name] = checked(name); }); + return s; } + function words(value) { return (value || '').split(' ').filter(Boolean); } + function anyOf(chosen, value) { return !chosen.length || chosen.indexOf(value) !== -1; } + function matches(li, s) { var d = li.dataset; if (s.words.some(function (w) { return d.search.indexOf(w) === -1; })) return false; - if (s.country !== 'all') { - var countries = (d.countries || d.country || '').split(/\s+/).filter(Boolean); - if (countries.indexOf(s.country) === -1) return false; - } - if (s.region) { - var regions = d.regions.split(' '); - if (regions.indexOf(s.region) === -1 && regions.indexOf(s.region.slice(0, 2) + '-*') === -1) return false; - } + if (s.where && words(d.where).indexOf(s.where) === -1) return false; var km = Number(d.km); if (km < s.min || km > s.max) return false; - if (d.kind === 'route' ? !s.route : !s.designated) return false; - if (s.line && d.line !== 'yes') return false; - if (s.policy && d.policy !== s.policy) return false; - if (s.tier && d.tier !== s.tier) return false; + if (!anyOf(s.time, d.time)) return false; + if (s.month && words(d.months).indexOf(s.month) === -1) return false; + if (s.terrain.length && !words(d.terrain).some(function (t) { return s.terrain.indexOf(t) !== -1; })) return false; + if (s.kind && d.kind !== s.kind) return false; + if (s.walking.length && !anyOf(s.walking, d.walking)) return false; + if (s.shape.length && !anyOf(s.shape, d.shape)) return false; + if (!anyOf(s.gpx, d.gpx)) return false; return true; } @@ -655,15 +681,12 @@ function toQuery(s) { var p = new URLSearchParams(); if (s.q) p.set('q', s.q); - if (s.country !== 'all') p.set('country', s.country); - if (s.region) p.set('region', s.region); + if (s.where) p.set('where', s.where); if (s.min) p.set('min', String(s.min)); if (s.max !== Infinity) p.set('max', String(s.max)); - if (s.designated !== s.route) p.set('kind', s.designated ? 'designated' : 'route'); - else if (!s.designated) p.set('kind', 'none'); - if (s.line) p.set('line', '1'); - if (s.policy) p.set('policy', s.policy); - if (s.tier) p.set('tier', s.tier); + if (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); return p.toString(); } @@ -671,25 +694,26 @@ function fromQuery() { var p = new URLSearchParams(window.location.search); el.q.value = p.get('q') || ''; - var country = p.get('country'); - syncRadios('#finder-form input[name="country"]', country === 'US' || country === 'CA' ? country : 'all'); - ['region', 'min', 'max', 'policy', 'tier'].forEach(function (name) { + var where = p.get('where') || p.get('region') || ''; + if (!where && (p.get('country') === 'US' || p.get('country') === 'CA')) where = p.get('country'); + el.where.value = hasOption(el.where, where) ? where : ''; + ['min', 'max', 'month'].forEach(function (name) { + if (!el[name]) return; var v = p.get(name) || ''; el[name].value = hasOption(el[name], v) ? v : ''; }); - var kind = p.get('kind'); - el.designated.checked = kind !== 'route' && kind !== 'none'; - el.route.checked = kind !== 'designated' && kind !== 'none'; - el.line.checked = p.get('line') === '1'; + var kind = p.get('kind') || ''; + if (kind === 'designated') kind = 'trail'; + syncRadios('#finder-form input[name="kind"]', kind === 'trail' || kind === 'route' ? kind : ''); + var lists = {}; + MULTI.forEach(function (name) { lists[name] = (p.get(name) || '').split(',').filter(Boolean); }); + if (p.get('line') === '1' && !lists.gpx.length) lists.gpx = ['here', 'partial']; + if (p.get('policy') && OLD_POLICY[p.get('policy')] && !lists.gpx.length) lists.gpx = [OLD_POLICY[p.get('policy')]]; + 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'; - limitRegions(); - } - - function limitRegions() { - var c = el.country.value; - el.region.querySelectorAll('optgroup').forEach(function (g) { g.disabled = c !== 'all' && g.dataset.country !== c; }); - if (el.region.value && c !== 'all' && el.region.value.slice(0, 2) !== c) el.region.value = ''; } function applySort() { @@ -697,6 +721,13 @@ 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); }); } @@ -709,21 +740,27 @@ li.hidden = !ok; if (ok) shown.push(li.dataset.id); }); - if (count && count.textContent !== shown.length + ' of ' + total + ' records') { + var noun = total === 1 ? ' trail' : ' trails'; + if (count && count.textContent !== shown.length + ' of ' + total + noun) { count.innerHTML = ''; var strong = document.createElement('strong'); strong.textContent = String(shown.length); count.appendChild(strong); - count.appendChild(document.createTextNode(' of ' + total + ' records')); + count.appendChild(document.createTextNode(' of ' + total + noun)); } empty.hidden = shown.length > 0; if (listHead) listHead.hidden = shown.length === 0; setText(lenHint, describeLength(s)); - var n = (s.words.length ? 1 : 0) + (s.country !== 'all' ? 1 : 0) + (s.region ? 1 : 0) + - (s.min ? 1 : 0) + (s.max !== Infinity ? 1 : 0) + (!s.designated ? 1 : 0) + (!s.route ? 1 : 0) + - (s.line ? 1 : 0) + (s.policy ? 1 : 0) + (s.tier ? 1 : 0); - active.textContent = n ? n + ' active' : ''; + /* Say how many trails a filter leaves out for having no value on file. */ + var on = { season: !!s.month, terrain: s.terrain.length > 0, walking: s.walking.length > 0, shape: s.shape.length > 0 }; + form.querySelectorAll('[data-missing]').forEach(function (note) { note.hidden = !on[note.dataset.missing]; }); + + var n = MORE.reduce(function (sum, name) { return sum + (s[name].length ? 1 : 0); }, 0); + active.textContent = n ? n + ' on' : ''; + var all = (s.where ? 1 : 0) + (s.min ? 1 : 0) + (s.max !== Infinity ? 1 : 0) + (s.month ? 1 : 0) + (s.kind ? 1 : 0) + + (s.time.length ? 1 : 0) + (s.terrain.length ? 1 : 0) + n; + setText(form.querySelector('.filters__count'), all ? all + ' on' : ''); maps.forEach(function (m) { if (m.kind === 'overview') setVisible(m, shown); }); if (updateUrl) { @@ -732,16 +769,10 @@ } } - form.querySelectorAll('input[name="country"]').forEach(function (r) { r.addEventListener('change', limitRegions); }); form.addEventListener('input', function () { apply(true); }); form.addEventListener('change', function () { apply(true); }); form.addEventListener('submit', function (e) { e.preventDefault(); }); - form.addEventListener('reset', function () { - setTimeout(function () { - el.region.querySelectorAll('optgroup').forEach(function (g) { g.disabled = false; }); - apply(true); - }, 0); - }); + form.addEventListener('reset', function () { setTimeout(function () { apply(true); }, 0); }); document.querySelectorAll('[data-reset]').forEach(function (b) { b.addEventListener('click', function () { form.reset(); el.q.focus(); }); }); @@ -761,17 +792,35 @@ apply(false); /* The count can announce from here on; the first application is done. */ setTimeout(function () { if (count) count.removeAttribute('aria-live'); }, 0); - /* The folded filters arrive closed; open them only where the filters - have their own column (the finder's wide layout), and leave them - closed on narrow screens. */ - if (more && window.matchMedia('(min-width: 70rem)').matches) more.open = true; + /* The filters behind "More" stay folded, unless the address already sets one. */ + var s0 = read(); + if (more && MORE.some(function (name) { return s0[name].length; })) more.open = true; + /* On a narrow screen the filters fold behind their heading, so the trails + come first; they stay open when the address already sets one. */ + var panel = form.querySelector('.filters__panel'); + var firstOn = s0.where || s0.min || s0.max !== Infinity || s0.month || s0.kind || s0.time.length || s0.terrain.length; + if (panel && window.matchMedia('(max-width: 63.99rem)').matches && !firstOn) panel.open = false; window.addEventListener('popstate', function () { fromQuery(); applySort(); apply(false); }); } var finder = document.getElementById('finder-form'); if (finder) initFinder(finder); - /* 4. Copy a required credit ------------------------------------------------ */ + /* 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. */ + function revealHash() { + var id = decodeURIComponent(window.location.hash.slice(1)); + var target = id && document.getElementById(id); + var opened = false; + for (var el = target; el; el = el.parentElement) { + if (el.tagName === 'DETAILS' && !el.open) { el.open = true; opened = true; } + } + if (opened) target.scrollIntoView(); + } + window.addEventListener('hashchange', revealHash); + if (window.location.hash) revealHash(); + + /* 5. Copy a required credit ------------------------------------------------ */ document.querySelectorAll('[data-copy]').forEach(function (button) { var target = document.querySelector(button.dataset.copy); diff --git a/web/assets/style.css b/web/assets/style.css index f37dfc8..7d826c9 100644 --- a/web/assets/style.css +++ b/web/assets/style.css @@ -730,7 +730,7 @@ code.raw { .hero { position: relative; overflow: hidden; - padding-block: var(--space-7) var(--space-6); + padding-block: var(--space-7) var(--space-5); } /* Decorative contour lines (not real terrain), faded toward the text */ .hero::before { @@ -759,21 +759,22 @@ code.raw { .finder__grid { display: grid; gap: var(--space-5) var(--space-6); - grid-template-areas: "head" "filters" "results"; + grid-template-areas: "filters" "main" "notes"; grid-template-columns: minmax(0, 1fr); } -.finder__head { grid-area: head; } .filters { grid-area: filters; } -.results { grid-area: results; container: results / inline-size; } -@media (min-width: 70rem) { +.finder__main { grid-area: main; display: grid; gap: var(--space-5); align-content: start; min-inline-size: 0; } +.results { container: results / inline-size; } +.finder__notes { grid-area: notes; display: grid; gap: var(--space-2); } +@media (min-width: 64rem) { .finder__grid { - grid-template-areas: "head head" "filters results"; - grid-template-columns: 17rem minmax(0, 1fr); + grid-template-areas: "filters main" ". notes"; + grid-template-columns: 18rem minmax(0, 1fr); } } /* Sticky only when the viewport can hold the whole form, so no part of it is trapped in a nested scroll box or cut off below the fold. */ -@media (min-width: 70rem) and (min-height: 70rem) { +@media (min-width: 64rem) and (min-height: 70rem) { .filters { position: sticky; inset-block-start: var(--space-4); align-self: start; } } @@ -909,7 +910,7 @@ code.raw { /* Without JavaScript the list is complete and readable; the controls that need it are hidden. */ html:not(.js) .filters, html:not(.js) .results-tools { display: none; } -html:not(.js) .finder__grid { grid-template-areas: "head" "results"; grid-template-columns: minmax(0, 1fr); } +html:not(.js) .finder__grid { grid-template-areas: "main" "notes"; grid-template-columns: minmax(0, 1fr); } /* 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 @@ -1003,7 +1004,7 @@ html:not(.js) .finder__grid { grid-template-areas: "head" "results"; grid-templa .line { display: grid; gap: 0.125rem; } .line__status { display: flex; - flex-wrap: wrap; + flex-wrap: nowrap; align-items: center; gap: var(--space-1) var(--space-2); font: 600 var(--step-0)/1.3 var(--font-sans); @@ -1037,7 +1038,7 @@ html:not(.js) .finder__grid { grid-template-areas: "head" "results"; grid-templa /* Column head, shown when rows are laid out as columns */ .list-head, .list-head[hidden] { display: none; } -@container results (min-width: 50rem) { +@container results (min-width: 66rem) { .entry { --plate-w: 7rem; grid-template-columns: var(--plate-w) minmax(0, 1fr) auto; @@ -1047,8 +1048,8 @@ html:not(.js) .finder__grid { grid-template-areas: "head" "results"; grid-templa } .entry__plate { aspect-ratio: 5 / 3; } .entry__facts { - grid-template-columns: 10rem 11rem; - gap: var(--space-5); + grid-template-columns: 9.5rem 6rem 7rem 6.5rem; + gap: var(--space-4); padding-block-start: 0; border-block-start: 0; } @@ -1058,7 +1059,7 @@ html:not(.js) .finder__grid { grid-template-areas: "head" "results"; grid-templa .list-head { display: grid; - grid-template-columns: 7rem minmax(0, 1fr) 10rem 11rem; + grid-template-columns: 7rem minmax(0, 1fr) 9.5rem 6rem 7rem 6.5rem; column-gap: var(--space-5); padding: 0 var(--space-2) var(--space-2); color: var(--ink-2); @@ -1136,20 +1137,35 @@ html:not(.js) .finder__grid { grid-template-areas: "head" "results"; grid-templa the viewport, so it scrolls with the page rather than sticking. */ .detail { display: grid; - gap: var(--space-6) var(--space-6); + gap: var(--space-5) var(--space-6); grid-template-columns: minmax(0, 1fr); - grid-template-areas: "map" "aside" "main"; + grid-template-areas: "glance" "map" "aside"; + align-items: start; } +.detail--with-profile { grid-template-areas: "glance" "map" "profile" "aside"; } +.detail__glance { grid-area: glance; min-inline-size: 0; } .detail__map { grid-area: map; min-inline-size: 0; } -.detail__main { grid-area: main; min-inline-size: 0; margin-block-start: var(--space-4); } +.detail__profile { grid-area: profile; min-inline-size: 0; } +.detail__main { min-inline-size: 0; } .detail__aside { grid-area: aside; min-inline-size: 0; } .detail__aside > * + * { margin-block-start: var(--space-5); } @media (min-width: 64rem) { .detail { grid-template-columns: minmax(0, 1fr) 22rem; grid-template-rows: auto 1fr; - grid-template-areas: "map aside" "main aside"; + grid-template-areas: "map glance" "map aside"; } + .detail--no-aside { grid-template-areas: "map glance" "map ."; } + .detail--with-profile { grid-template-rows: auto 1fr auto; grid-template-areas: "map glance" "map aside" "profile profile"; } + .detail--with-profile.detail--no-aside { grid-template-areas: "map glance" "map ." "profile profile"; } + /* The map fills the height of the column beside it, so a long column of + facts and downloads leaves no empty space under the map. */ + .detail__map { align-self: stretch; display: flex; flex-direction: column; } + .detail__map > .mapfig__frame { flex: 1 1 auto; display: flex; flex-direction: column; } + .detail__map .map { flex: 1 1 auto; aspect-ratio: auto; min-block-size: 30rem; } + /* With no track there is no map to stretch: the notice keeps its own height. */ + .detail--no-map .detail__map { align-self: start; } + .detail--no-map .detail__map .map { flex: 0 0 auto; min-block-size: 22rem; } } .block + .block { margin-block-start: var(--space-7); } @@ -1436,6 +1452,14 @@ td .linklist a { font-weight: 400; } .route-item { padding: var(--space-4); background: var(--surface); border: 1px solid var(--rule-strong); } .route-item h4 { font-family: var(--font-serif); font-size: var(--step-1); } .route-item__meta { margin-block-start: var(--space-2); font: 400 var(--step--1)/1.5 var(--font-sans); color: var(--ink-2); } +/* A route's guides in its list row: one compact line under the name, not a + column of their own. */ +.entry__guides { grid-column: 1 / -1; display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 0 var(--space-3); align-items: baseline; } +.entry__guides .route-item__guides-label { margin-block-start: 0; } +.entry__guides .route-guides { display: grid; gap: var(--space-1); margin-block-start: 0; padding: 0; list-style: none; } +@container results (min-width: 66rem) { + .entry__guides { grid-column: 2 / -1; } +} .route-item__guides-label { margin-block-start: var(--space-3); font: 600 var(--step--2)/1.3 var(--font-sans); letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-2); } .route-guides { margin-block-start: var(--space-1); padding-inline-start: 1.2rem; font: 400 var(--step--1)/1.5 var(--font-sans); } .route-guides li + li { margin-block-start: var(--space-1); } @@ -1488,3 +1512,310 @@ td .linklist a { font-weight: 400; } } .notfound-search .field__label { grid-column: 1 / -1; } .notfound-search .input { min-inline-size: 0; } + +/* 11. Hiker pages: the top of a trail page, collections ------------------- */ + +.trail-lede { max-inline-size: 46rem; font-size: var(--step-1); line-height: 1.5; text-wrap: pretty; } +.trail-actions { margin-block-start: var(--space-4); } +.page-head .titleblock { margin-block-end: var(--space-4); } + +/* At a glance: the hiker's facts, a legend box like the panels */ +.glance { border: 1px solid var(--ink); background: var(--surface); } +.glance__title { + padding: var(--space-2) var(--space-4); + background: var(--ink); + color: var(--paper); + font: 600 var(--step--1)/1.3 var(--font-sans); + letter-spacing: 0.08em; + text-transform: uppercase; +} +.glance__facts { + --len-size: var(--step-2); + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + column-gap: var(--space-4); + padding: var(--space-1) var(--space-4) var(--space-3); +} +.glance__facts > div { padding-block: var(--space-3); border-block-start: 1px dotted var(--rule-strong); min-inline-size: 0; } +.glance__facts > div:first-child, +.glance__facts > div:nth-child(2):not(.glance__wide) { border-block-start: 0; } +.glance__wide { grid-column: 1 / -1; } +.glance dt { + color: var(--ink-2); + font: 600 var(--step--2)/1.3 var(--font-sans); + letter-spacing: 0.08em; + text-transform: uppercase; +} +.glance dd { margin: var(--space-1) 0 0; font: 500 var(--step-0)/1.4 var(--font-sans); overflow-wrap: anywhere; } +.glance dd small { display: block; margin-block-start: var(--space-1); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); } +.glance__to { color: var(--ink-2); } +.glance__warn { + margin: 0 var(--space-4) var(--space-4); + padding: var(--space-2) var(--space-3); + background: var(--highlight); + border-inline-start: 3px solid var(--route); + font: 400 var(--step--1)/1.45 var(--font-sans); +} +.glance > .note { padding: 0 var(--space-4) var(--space-4); } + +/* Elevation profile: a legend box like the glance, the line drawn as SVG */ +.elev { border: 1px solid var(--ink); background: var(--surface); } +.elev__title { + padding: var(--space-2) var(--space-4); + background: var(--ink); + color: var(--paper); + font: 600 var(--step--1)/1.3 var(--font-sans); + letter-spacing: 0.08em; + text-transform: uppercase; +} +.elev__body { padding: var(--space-4); font: 400 var(--step-0)/1.5 var(--font-sans); } +.elev__body > * + * { margin-block-start: var(--space-3); } +.elev__figure { padding: var(--space-3) var(--space-4) var(--space-4); } +.elev__figure figcaption { margin-block-start: var(--space-2); color: var(--ink-2); font: 400 var(--step--1)/1.5 var(--font-sans); } +.elev__figure figcaption > * + * { margin-block-start: var(--space-2); } +.elev-profile { display: block; inline-size: 100%; block-size: auto; } +.elev-profile text { fill: var(--ink-2); font-family: var(--font-sans); } +.elev-profile__tick { font-size: 12px; font-variant-numeric: tabular-nums; } +.elev-profile__axis { font-size: 12px; font-weight: 600; } +.elev-profile__grid { stroke: var(--rule); stroke-width: 1; } +.elev-profile__frame { stroke: var(--rule-strong); stroke-width: 1; } +.elev-profile__line { fill: none; stroke: var(--trail); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; } +.elev-profile__mark { fill: var(--surface); stroke: var(--trail); stroke-width: 2; } +/* One axis system at a time, by the reader's unit preference */ +.elev-profile .len__mi { display: none; } +:root[data-units="mi"] .elev-profile .len__mi { display: inline; } +:root[data-units="mi"] .elev-profile .len__km { display: none; } + +/* Below the hiker's part: the plain foot line, then "About this data" */ +.trail-more { padding-block: var(--space-6) var(--space-7); } +.page-foot { + max-inline-size: var(--measure); + margin-block-end: var(--space-5); + color: var(--ink-2); + font: 400 var(--step--1)/1.5 var(--font-sans); +} +.about-data { border: 1px solid var(--rule-strong); background: var(--surface); } +.about-data > summary { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--space-1) var(--space-4); + align-items: center; + padding: var(--space-4) var(--space-5); + cursor: pointer; + list-style: none; +} +.about-data > summary::-webkit-details-marker { display: none; } +.about-data > summary h2 { font-size: var(--step-2); } +.about-data__hint { grid-column: 1; color: var(--ink-2); font: 400 var(--step--1)/1.45 var(--font-sans); } +.about-data > summary::after { + content: ""; + grid-column: 2; + grid-row: 1 / span 2; + inline-size: 0.6rem; + block-size: 0.6rem; + border: solid currentColor; + border-width: 0 2px 2px 0; + transform: translateY(-25%) rotate(45deg); +} +.about-data[open] > summary::after { transform: translateY(25%) rotate(-135deg); } +.about-data > summary:focus-visible { outline-offset: -5px; } +.about-data__body { max-inline-size: 54rem; padding: var(--space-5); border-block-start: 1px solid var(--rule); } +.about-data__body > .rawrecord { margin-block-start: var(--space-7); } + +/* Home: collections ("Ways in") and states */ +.mapfig--wide { --map-ratio: 2 / 1; } +@media (max-width: 40rem) { .mapfig--wide { --map-ratio: 1 / 1; } } +.shelves { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(min(100%, 17rem), 1fr)); + gap: var(--space-4); + padding: 0; + list-style: none; +} +.shelf { + display: grid; + grid-template-rows: auto auto 1fr auto; + gap: var(--space-2); + padding: var(--space-4); + background: var(--surface); + border: 1px solid var(--ink); + border-block-start-width: 4px; +} +.shelf__title { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-3); font-size: var(--step-1); line-height: 1.25; } +.shelf__title a { color: var(--ink); text-decoration-color: var(--rule-strong); } +.shelf__count { color: var(--ink-2); font: 600 var(--step--1)/1 var(--font-sans); font-variant-numeric: tabular-nums; } +.shelf__blurb { color: var(--ink-2); font: 400 var(--step--1)/1.45 var(--font-sans); } +.shelf__items { padding: 0; list-style: none; font: 400 var(--step--1)/1.35 var(--font-sans); } +.shelf__items li { display: flex; justify-content: space-between; gap: var(--space-3); padding-block: 0.3rem; border-block-start: 1px dotted var(--rule); } +.shelf__items a { color: var(--ink); } +.shelf__len { flex: none; color: var(--ink-2); font-variant-numeric: tabular-nums; } +.shelf__more { font: 600 var(--step--1)/1.3 var(--font-sans); } +/* One unit only in a card row, the reader's */ +.len--short .len__mi { display: none; } +:root[data-units="mi"] .len--short .len__mi { display: inline; } +:root[data-units="mi"] .len--short .len__km { display: none; } + +.region-chips { margin-block-start: var(--space-6); } +.region-chips h3 { margin-block-end: var(--space-3); font-size: var(--step-1); } +.chips { display: flex; flex-wrap: wrap; gap: var(--space-2); padding: 0; list-style: none; } +.chips a { + display: inline-flex; + align-items: center; + gap: var(--space-2); + min-block-size: 2.75rem; + padding: 0 var(--space-3); + border: 1px solid var(--rule-strong); + border-radius: 999px; + background: var(--surface); + color: var(--ink); + font: 500 var(--step--1)/1.2 var(--font-sans); + text-decoration: none; +} +.chips a:hover { border-color: var(--ink); } +.chips__n { color: var(--ink-2); font-variant-numeric: tabular-nums; } + +.entry__days { display: block; margin-block-start: var(--space-1); color: var(--ink-2); font: 400 var(--step--1)/1.3 var(--font-sans); } +.finder__foot { max-inline-size: var(--measure); color: var(--ink-2); font: 400 var(--step--1)/1.5 var(--font-sans); } +.filters__reset { padding-block-start: var(--space-4) !important; } +/* Narrow screens: a card is its title, count and rule; the trail names are on its page. */ +@media (max-width: 40rem) { + .shelf { grid-template-rows: auto; padding: var(--space-3) var(--space-4); } + .shelf__items, .shelf__more { display: none; } +} + +/* 12. Catalogue, places, lists, onward ---------------------------------------- */ + +.hero--short { padding-block: var(--space-6) var(--space-4); } +.hero--short .hero__inner { gap: var(--space-4); } +.lists-row { display: grid; gap: var(--space-2); } +.lists-row__title { font: 600 var(--step--2)/1.3 var(--font-sans); letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-2); } +.section--finder { padding-block-start: var(--space-4); } +.filters__first { display: grid; gap: var(--space-4); padding: 0 var(--space-4) var(--space-4); } +.filters__first .field + .field { padding-block-start: var(--space-4); border-block-start: 1px dotted var(--rule-strong); } +.filters__form .field + .field { padding-block-start: var(--space-4); border-block-start: 1px dotted var(--rule-strong); } +@media (min-width: 40rem) and (max-width: 63.99rem) { + .filters__first { grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: var(--space-5); } + .filters__first .field:nth-child(2) { padding-block-start: 0; border-block-start: 0; } +} +.pills { display: flex; flex-wrap: wrap; gap: var(--space-2); } +.pills .check { grid-template-columns: auto auto; padding: 0.15rem var(--space-2); border: 1px solid var(--rule-strong); border-radius: 999px; } +.pills .check:has(input:checked) { border-color: var(--ink); background: var(--sunken); } +.filter-missing { padding: var(--space-2); border-inline-start: 3px solid var(--route); background: var(--hatch-fill); color: var(--ink); } +.filter-missing[hidden] { display: none; } +.seg span { text-align: center; } +a.tag { text-decoration: none; } +a.tag:hover { background: var(--sunken); } +.entry__by { color: var(--ink); font: 500 var(--step--1)/1.35 var(--font-sans); } +.entry__time dd { font: 500 var(--step-0)/1.3 var(--font-sans); } +.entry__est { display: block; color: var(--ink-2); font: 400 var(--step--2)/1.3 var(--font-sans); letter-spacing: 0.04em; text-transform: uppercase; } +.results__group { margin-block: var(--space-6) var(--space-2); font-size: var(--step-1); } + +/* "What is a route?" beside the Kind line of a route's page */ +.define { font: 400 var(--step--1)/1.45 var(--font-sans); color: var(--ink-2); } +.define > summary { inline-size: fit-content; color: var(--link); cursor: pointer; text-decoration: underline; text-underline-offset: 0.16em; } +.define > p { max-inline-size: 40rem; margin-block-start: var(--space-2); padding: var(--space-2) var(--space-3); border-inline-start: 3px solid var(--route); background: var(--surface); color: var(--ink); } + +/* Ways onward at the foot of a trail page */ +.onward { margin-block-end: var(--space-6); } +.onward > h2 { margin-block-end: var(--space-4); font-size: var(--step-2); } +.onward__grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 17rem), 1fr)); gap: var(--space-4); } +.onward__part { padding: var(--space-4); background: var(--surface); border: 1px solid var(--rule-strong); border-block-start: 3px solid var(--ink); } +.onward__part h3 { margin-block-end: var(--space-2); font-size: var(--step-0); } +.onward__list { padding: 0; list-style: none; font: 400 var(--step--1)/1.35 var(--font-sans); } +.onward__list li { display: flex; justify-content: space-between; gap: var(--space-3); padding-block: 0.35rem; border-block-start: 1px dotted var(--rule); } +.onward__list li:first-child { border-block-start: 0; } +.onward__list a { color: var(--ink); } +.onward__len { flex: none; color: var(--ink-2); font-variant-numeric: tabular-nums; display: inline-flex; gap: 0.3em; } +.onward__more { margin-block-start: var(--space-2); font: 600 var(--step--1)/1.3 var(--font-sans); } + +/* Places hub */ +.places { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 19rem), 1fr)); gap: var(--space-5); } +.places__group { padding: var(--space-4); background: var(--surface); border: 1px solid var(--ink); border-block-start-width: 4px; } +.places__group h2 { font-size: var(--step-2); } +.places__sum { margin-block: var(--space-2) var(--space-3); color: var(--ink-2); font: 400 var(--step--1)/1.45 var(--font-sans); } +.places__list { padding: 0; list-style: none; font: 400 var(--step-0)/1.35 var(--font-sans); } +.places__list li { display: flex; justify-content: space-between; gap: var(--space-3); padding-block: 0.4rem; border-block-start: 1px dotted var(--rule); } +.places__list li:first-child { border-block-start: 0; } +.places__n { flex: none; color: var(--ink-2); font-size: var(--step--1); font-variant-numeric: tabular-nums; } +.page-head .chips { margin-block-start: var(--space-2); } +.place > * + * { margin-block-start: var(--space-6); } + +/* About hub */ +.about-hub__list { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 16rem), 1fr)); gap: 0 var(--space-5); max-inline-size: none; } +.about-hub__list li, .about-hub__list li:first-child { padding-block: var(--space-2); border-block-start: 0; border-block-end: 1px dotted var(--rule-strong); } +.doc section > * + * { margin-block-start: var(--space-4); } +.doc section + section { margin-block-start: var(--space-7); } + +.filters__panel > summary { + display: flex; align-items: center; gap: var(--space-3); + padding: var(--space-2) var(--space-4); min-block-size: 2.75rem; + border-block: 1px solid var(--ink); + font: 600 var(--step--1)/1.3 var(--font-sans); letter-spacing: 0.08em; text-transform: uppercase; + cursor: pointer; list-style: none; +} +.filters__panel > summary::-webkit-details-marker { display: none; } +.filters__panel > summary::after { + content: ""; margin-inline-start: auto; inline-size: 0.5rem; block-size: 0.5rem; + border: solid currentColor; border-width: 0 2px 2px 0; transform: translateY(-25%) rotate(45deg); +} +.filters__panel[open] > summary::after { transform: translateY(25%) rotate(-135deg); } +.filters__panel[open] > summary { margin-block-end: var(--space-4); } +.filters__count:not(:empty) { padding: 0 var(--space-2); border-radius: 999px; background: var(--ink); color: var(--paper); letter-spacing: 0.02em; text-transform: none; } +@media (min-width: 64rem) { + .filters__panel > summary { display: none; } +} + +/* The trail list where there is no room for columns (a phone, or beside the + filters on a laptop): a compact card, not a table folded in on itself. Name, one or two lines of description, the place, then the facts on + one wrapping line ("420 km · About 4 weeks · Partial GPX here"). The labels, + the length strip, the second unit and the boxed notes are for wide rows; the + trail's own page has all of it. */ +@container results (max-width: 65.99rem) { + /* With the statuses written out in each card, the list needs no key. */ + .key { display: none; } + .entry { + --plate-w: 3.75rem; + grid-template-areas: "plate body" ". facts" ". note"; + gap: var(--space-2) var(--space-3); + padding: var(--space-4) 0; + } + .entry__desc { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; } + .entry__facts { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0; + /* Each fact carries its dot in its own left padding, and the row is pulled + left by that padding and clipped, so a fact that starts a line shows no dot. */ + margin-inline-start: -1.1em; + clip-path: inset(0 0 0 1.1em); + padding-block-start: 0; + border-block-start: 0; + font: 400 var(--step--1)/1.5 var(--font-sans); + color: var(--ink); + } + .entry__facts > div { position: relative; display: inline-flex; align-items: baseline; padding-inline-start: 1.1em; } + .entry__facts > div::before { content: "\00B7"; position: absolute; inset-inline-start: 0.4em; color: var(--ink-2); } + .entry__facts dt { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .entry__facts dd { margin: 0; font: inherit; } + .entry__facts .len--stack { display: inline; } + :root:not([data-units="mi"]) .entry__facts .len--stack .len__km, + :root[data-units="mi"] .entry__facts .len--stack .len__mi { font: 600 var(--step--1)/1.5 var(--font-sans); } + :root:not([data-units="mi"]) .entry__facts .len--stack .len__mi, + :root[data-units="mi"] .entry__facts .len--stack .len__km { display: none; } + .entry__facts .loglen, + .entry__facts .swatch, + .entry__facts .line__detail, + .entry__facts .entry__partial, + .entry__facts > .entry__climb { display: none; } + .entry__time dd { font: inherit; } + .entry__facts .entry__est { display: inline; margin-inline-start: 0.35em; } + .entry__facts .line { display: inline; } + .entry__facts .line__status { display: inline; font: inherit; } + .entry__guides { grid-column: 2 / -1; grid-template-columns: minmax(0, 1fr); } +} +/* A wider card has room for a larger logo. */ +@container results (min-width: 34rem) and (max-width: 65.99rem) { + .entry { --plate-w: 6rem; gap: var(--space-2) var(--space-4); } +} +.line__status .swatch { flex: none; } diff --git a/web/olt/browse.py b/web/olt/browse.py new file mode 100644 index 0000000..2061fb9 --- /dev/null +++ b/web/olt/browse.py @@ -0,0 +1,111 @@ +"""Lists: ready-made selections of trails, each a rule over a trail's attributes (olt/facets.py). + +A list is defined once, here, as a test on a trail. No list names a trail by +id: membership follows the records, so a new trail or a new [hike] table moves +trails in and out of lists with no change to this file. + +A list is shown (on the home page, on /lists/, and with a page of its own) +only when it is useful with today's trails: + + MIN_SIZE at least this many trails (fewer reads as a gap, not a list) + MAX_SHARE at most this share of all trails (more is nearly everything) + +Every list has its page at /lists//, except Routes, which keeps /routes/. +""" +from dataclasses import dataclass +from typing import Callable + +from . import common, facets, words + +MIN_SIZE = 4 +MAX_SHARE = 0.75 + +LONG_KM = 2000 +SHORT_KM = 100 + + +@dataclass(frozen=True) +class List: + key: str + 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"] + + +def _mi(km): + return words.fmt_int(words.km_to_mi(km)) + + +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.", + facets.is_national), + List("routes", "Routes", facets.ROUTE_DEFINITION, + 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), + 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"]), + 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), + 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), + List("loops", "Loops", "Trails that finish where they start.", + lambda r: facets.shape(r) == "loop"), + List("with-gpx", "With a GPX to download", + "Trails with a GPX file of the track on their page.", + facets.gpx_here), + List("canada", "In Canada", "Trails in Canada, or crossing into it.", + lambda r: "CA" in common.countries(r)), + List("united-states", "In the United States", "Trails in the United States, or crossing into it.", + lambda r: "US" in common.countries(r)), + List("off-trail", "Cross-country", + "Trails with stretches of walking where there is no trail.", + lambda r: facets.walking(r) in facets.CROSS_COUNTRY), +) + tuple( + List(f"terrain-{t}", label, f"Trails with {t} among their main terrain.", + lambda r, t=t: t in facets.terrain(r)) + for t, label in words.TERRAIN.items() +) + + +def members(lst, records): + return sorted((r for r in records if lst.test(r)), key=lambda r: (lst.order(r), r["name"])) + + +def is_shown(n, total): + """The threshold rule: a list is shown when it holds at least MIN_SIZE + trails and no more than MAX_SHARE of all of them.""" + return n >= MIN_SIZE and n <= MAX_SHARE * total + + +def shown(records): + """[(list, its trails)] for every list that passes is_shown, in LISTS order.""" + out = [] + for lst in LISTS: + recs = members(lst, records) + if is_shown(len(recs), len(records)): + out.append((lst, recs)) + return out + + +def by_key(key): + return next(lst for lst in LISTS if lst.key == key) + + +def path(lst): + return "/routes/" if lst.key == "routes" else f"/lists/{lst.key}/" diff --git a/web/olt/common.py b/web/olt/common.py index 5b35cd9..769b15b 100644 --- a/web/olt/common.py +++ b/web/olt/common.py @@ -129,39 +129,15 @@ def absent_reason_short(rec): return re.sub(r"^No (?:line|track) is included\.\s*", "", reason) or reason -def regions_html(rec, linked=False): - """Region codes with their names; optionally each linked to the filtered list.""" - parts = [] - for code in rec.get("regions", []): - name = words.region_name(code) - if code == words.ALL_CANADA: - text = Markup(esc(name)) - href = "/regions/#canada-wide" - else: - text = Markup(f'{esc(code)}') - href = f"/regions/{words.region_key(code, rec['country']).lower()}/" - if linked: - text = Markup(f'{text}') - parts.append(text) - return Markup(" ".join(parts)) - - -def tags(rec, with_policy=True): - """Kind, tier and listing tags, and (with_policy) the track policy of a route.""" +def badges(rec, *, route_tag=True): + """The badges a hiker needs on a row or a trail page: Route (linked to what a route is) + and National Scenic Trail. An official trail has no badge for its kind. + route_tag=False leaves the Route badge out (the Routes list, where every row is one).""" out = [] - if is_route(rec): - out.append('Person-defined route') - elif rec.get("tier") == "national": + if route_tag and is_route(rec): + out.append('Route') + if rec.get("tier") == "national": out.append('National Scenic Trail') - else: - out.append('Designated trail') - tier = rec.get("tier") - if tier in ("short", "deferred", "candidate"): - out.append(f'{esc(words.label(words.TIERS, tier))}') - if str(rec.get("wave")) == "held": - out.append('Held') - if is_route(rec) and with_policy: - out.append(policy_chip(policy(rec))) return Markup("".join(out)) diff --git a/web/olt/docs.py b/web/olt/docs.py index b423abf..e9df902 100644 --- a/web/olt/docs.py +++ b/web/olt/docs.py @@ -8,7 +8,7 @@ import collections import os import re -from . import common, md, words +from . import common, elevation, facets, md, words from .markup import Markup, esc REAL_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) @@ -178,7 +178,23 @@ def sources_page(records, site, repo_root): return Markup(f'{esc(words.label(words.LICENCES, k))} {esc(k)}') head = ('{0}Records' - 'With a trackTrails and routes') + 'With a trackTrails') + elev_models = {} + for r in records: + src = (elevation.get(r) or {}).get("source") or {} + if src.get("attribution"): + key = (src.get("model", ""), src.get("url", ""), src["attribution"]) + elev_models[key] = elev_models.get(key, 0) + 1 + elev_credit = "" + if elev_models: + items = "" + for (model, url, attribution), n in sorted(elev_models.items()): + model_html = (f'{esc(model)}' if url else esc(model)) if model else "The elevation model" + items += (f'

{model_html}, used for {n} trail{"s" if n != 1 else ""}.

' + f'

{esc(attribution)}

') + elev_credit = (f'

Elevation model

' + f'

The elevation figures and profiles on the trail pages were computed ' + f'from each track and this model. Its credit, as it gives it:

{items}
') computed = f"""

At a glance

Counted from the {len(records)} records. Each trail page names its own source, licence and credit. @@ -191,10 +207,11 @@ def sources_page(records, site, repo_root):

By track source

{head.format("Track source")} {group_rows(by_source, source_label)}
+ {elev_credit}
""" doc_html = render_doc(read_doc(repo_root, "SOURCES.md"), site, drop_h1=True) - body = (f'
' - f'

Provenance

Sources

' + body = (f'
{BREAD}
  • Sources
  • ' + f'

    Sources

    ' f'

    Where the tracks come from, and the terms each source states.

    ' f'
    {computed}' f'
    {doc_html}
    ') @@ -224,8 +241,8 @@ def logos_page(records, site, repo_root):
    Taken from
    {src_html}
    """ counts = collections.Counter(r.get("shield", {}).get("status", "") for r in records) - body = f"""
    -

    Marks

    Logos

    + body = f"""
    {BREAD}
  • Logos
  • +

    Logos

    Logos are shown only to identify each trail. They belong to their holders.

    {notice_html}{f'

    Ask for a track or logo to be removed, or its credit changed.

    ' if site.is_github else ""}
    @@ -238,27 +255,121 @@ logo not found (logo-not-found).

    """ return "Logos", "Trail logos, their holders, and how a holder can ask for removal.", Markup(body) +BREAD = Markup('
    + +
    +
    +

    What this is

    +

    {esc(site.name)} lists {n} long-distance trails in the United States and Canada: where each one goes, +how long it is and takes, when to walk it, and where to get its track. It is built, page by page, from an +open dataset of one text file per trail. Everything a page says about a trail comes from that file. +{f'The dataset is kept in a public repository, where anyone can propose a change.' if site.repo_url else ""}

    +

    The dataset calls each trail a record, and the pages under About use its terms. The rest of the +site calls them trails.

    +{what} +
    + +

    How trails are chosen

    +

    A trail is listed when it is a named, continuous walk, or a named loop, of at least 80 km (50 miles) +in the United States or Canada. It is either an official trail, looked after as one trail by a land agency or +a trail association, or a route: {esc(facets.ROUTE_DEFINITION[0].lower() + facets.ROUTE_DEFINITION[1:])} +{routes} of the {n} trails are routes. Every National Scenic Trail is listed, and a few well-known multi-day +trails between 60 and 80 km.

    +

    Each record has a tier, which says why it is listed. A record can also be held: listed, +but with something about it not yet settled, which its note says.

    +
    +{tier_rows}
    TierWhat it meansRecords
    Held wave = "held"{esc(words.meaning(words.WAVES, "held"))}. Any tier can be held.{held}
    +

    These states are for keeping the dataset. They are not shown when browsing trails, and they do not change +what a trail page says about walking it. Each trail page shows its own under “About this data”.

    +{rule} +
    + +

    When a GPX is included

    +

    A track is included, as GPX and GeoJSON, only where its source’s terms allow passing it on. +{lines} of the {n} trails have one. Where there is none, the trail’s page says why and where to look. +Each track keeps its source’s terms; the credit and licence are shown beside every map and download.

    +

    A route’s track follows its author’s choice. The dataset records that choice as the route’s +track policy:

    +
    +{policy_rows}
    Track policyWhat it means hereRoutes
    +

    The author of a route who wants its record changed or removed can ask; see Logos for how, +or use the links below.

    +
    + +

    Correct or add a trail

    +

    Every trail page has a “Report a problem” link. Please say where a correction can be checked: +a source page, a map, or a measured track.

    +{forms} +{rest} +{contrib} +
    +
    """ + return "About", f"What {site.name} is, how trails are chosen, the data and its sources, and how to correct or add a trail.", Markup(body) def _size(out_dir, relpath): @@ -337,8 +448,8 @@ def data_page(records, site, repo_root, out_dir): ] lrow = "".join(f'{esc(a)}{esc(b)}{esc(c)}' for a, b, c in lic_rows) - body = f"""
    -

    Downloads

    Data

    + body = f"""
    {BREAD}
  • Data
  • +

    Data and downloads

    Bulk files, the stable per-trail URLs, and the licences.

    Bulk downloads

    {len(records)} records. Sizes are this build's.

    @@ -373,7 +484,7 @@ def data_page(records, site, repo_root, out_dir): def schema_page(site, repo_root): doc_html = render_doc(read_doc(repo_root, "docs/schema.md"), site, drop_h1=True) body = f"""
    -

    Reference

    Record schema

    @@ -384,7 +495,7 @@ def schema_page(site, repo_root): def changelog_page(site, repo_root): doc_html = render_doc(read_doc(repo_root, "CHANGELOG.md"), site, drop_h1=True) body = f"""
    -

    Reference

    Changelog

    diff --git a/web/olt/elevation.py b/web/olt/elevation.py new file mode 100644 index 0000000..6be9b7f --- /dev/null +++ b/web/olt/elevation.py @@ -0,0 +1,286 @@ +"""Elevation facts and the profile, from a trail's elevation.json (docs/schema.md). + +The file beside each record holds figures computed from its track and a public +elevation model. This module loads it, states the rules that decide what a page +may honestly show, and draws the profile as SVG at build time. + +Rules, all on the file's own fields: + coverage below LOW_COVERAGE: the figures describe the track only. + coverage above HIGH_COVERAGE: the track includes more than the trail, so + the climb is overstated. + parts above PROFILE_MAX_PARTS: the parts are not in walking order, so no + profile is drawn; the figures are still shown. + descent is shown beside the climb only when it differs by more than + DESCENT_DIFF of the larger figure. +""" +import json +import math +import os +from collections import Counter + +from . import words +from .markup import Markup, esc + +LOW_COVERAGE = 0.85 +HIGH_COVERAGE = 1.15 +PROFILE_MAX_PARTS = 10 +DESCENT_DIFF = 0.05 + +COMPUTED_NOTE = "Computed from the track." + +_REQUIRED = ("highest", "lowest", "ascent_m", "descent_m", "track_km", + "published_km", "coverage", "parts", "orientation", "profile", "source") + + +def load_file(root, tid): + """The parsed elevation.json of one trail, or None when it has none or it + does not hold the fields a page needs.""" + path = os.path.join(root, tid, "elevation.json") + if not os.path.isfile(path): + return None + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + except (OSError, ValueError): + return None + if not isinstance(data, dict) or any(k not in data for k in _REQUIRED): + return None + if not all(isinstance(data[k], dict) and "m" in data[k] for k in ("highest", "lowest")): + return None + if not isinstance(data.get("source"), dict) or not isinstance(data.get("profile"), list): + return None + return data + + +def get(rec): + """A record's elevation facts (derived.elevation), or None.""" + value = rec.get("derived", {}).get("elevation") + return value if isinstance(value, dict) else None + + +def direction_words(elev): + """"walking south to north", from the file's orientation.""" + text = str(elev.get("orientation", "")).replace("-", " ") + return f"walking {text}" if text else "" + + +def coverage_kind(elev): + """"partial" well under 1, "over" well over 1, else "".""" + cov = elev.get("coverage") + if not isinstance(cov, (int, float)): + return "" + if cov < LOW_COVERAGE: + return "partial" + if cov > HIGH_COVERAGE: + return "over" + return "" + + +def coverage_percent(elev): + """"about 59%", or "less than 1%" for a track that barely exists.""" + pct = (elev.get("coverage") or 0) * 100 + if pct < 1: + return "less than 1%" + return f"about {round(pct):,}%" + + +def coverage_caveat(elev): + """What the coverage means for the figures, or "" when it is near 1.""" + kind = coverage_kind(elev) + if kind == "partial": + return ("The elevation figures are for the track only. The track covers " + f"{coverage_percent(elev)} of the published length.") + if kind == "over": + return ("The track is longer than the published length " + f"({coverage_percent(elev)} of it). It includes more than the trail, such as " + "side trails or alternates, so the climb is overstated.") + return "" + + +def show_descent(elev): + """True when descent differs from ascent by more than a few percent.""" + up, down = elev.get("ascent_m") or 0, elev.get("descent_m") or 0 + bigger = max(up, down) + return bool(bigger) and abs(up - down) / bigger > DESCENT_DIFF + + +def show_profile(elev): + """True when a profile may be drawn: few enough parts to be in walking order.""" + return (elev.get("parts") or 0) <= PROFILE_MAX_PARTS and len(elev.get("profile") or []) >= 2 + + +def parts_caveat(elev): + """Why no profile is drawn, when the track is in too many parts.""" + if len(elev.get("profile") or []) < 2: + return "No profile is drawn. The track has too few sampled points to draw one." + parts = elev.get("parts") or 0 + if parts <= PROFILE_MAX_PARTS: + return "" + return (f"No profile is drawn. The track is in many parts ({parts} in the elevation " + "sampling) and they are not in walking order, so a line through them would not " + "be the walk. The figures above are still from the whole track, with no climb " + "counted across a gap.") + + +def plain_elevation(m): + """"2,025 m (6,644 ft)", for a sentence or a text alternative.""" + return f"{words.fmt_int(m)} m ({words.fmt_int(m / words.M_PER_FT)} ft)" + + +def plain_length(km): + return f"{words.fmt_km1(km)} km ({words.fmt_int(words.km_to_mi(km))} mi)" + + +def is_sea_level(point): + return (point or {}).get("m") == 0 + + +def summary_sentence(elev, loop=False): + """The facts in one sentence: the profile's text alternative.""" + high, low = elev["highest"]["m"], elev["lowest"]["m"] + direction = "" if loop else f", {direction_words(elev)}" + low_text = "sea level" if low == 0 else plain_elevation(low) + text = (f"Computed from the track{direction}, the trail climbs " + f"{plain_elevation(elev['ascent_m'])} in total over {plain_length(elev['track_km'])} " + f"of track, between a low point of {low_text} and a high point of {plain_elevation(high)}") + if show_descent(elev): + text += f", and descends {plain_elevation(elev['descent_m'])}" + return text + "." + + +# The profile ---------------------------------------------------------------- + +def segments(profile, part_starts=()): + """The profile split into its parts. A part's first point repeats the + distance of the point before it (docs/schema.md), and part_starts_km names + those distances; a new part starts there, never joined to the last.""" + starts = Counter(part_starts or ()) + out, current, prev = [], [], None + for point in profile or (): + dist = point[0] + if current and dist <= prev and (dist < prev or starts.get(dist, 0) or not starts): + if starts.get(dist, 0): + starts[dist] -= 1 + out.append(current) + current = [] + current.append(point) + prev = dist + if current: + out.append(current) + return out + + +def _nice_step(span, target=5): + if span <= 0: + return 1.0 + raw = span / target + mag = 10 ** math.floor(math.log10(raw)) + for mult in (1, 2, 5, 10): + if raw <= mult * mag: + return float(mult * mag) + return float(10 * mag) + + +def _ticks(lo, hi, target=5): + step = _nice_step(hi - lo, target) + value = math.ceil(lo / step) * step + out = [] + while value <= hi + step * 1e-9: + out.append(round(value, 10)) + value += step + return out, step + + +def _fmt_tick(value, step): + if step >= 1: + return f"{round(value):,}" + text = f"{value:.2f}".rstrip("0").rstrip(".") + return text + + +W, H = 680, 270 +LEFT, RIGHT, TOP, BOTTOM = 58, 14, 14, 40 + + +def profile_svg(elev, loop=False): + """The profile as inline SVG, drawn now, not by a script. Both unit systems + are drawn; CSS shows one, through the same len__km / len__mi pair and the + reader's unit preference as every length on the site.""" + profile = elev.get("profile") or [] + if len(profile) < 2: + return Markup("") + plot_w, plot_h = W - LEFT - RIGHT, H - TOP - BOTTOM + x_max = max(float(elev.get("track_km") or 0), max(p[0] for p in profile), 0.001) + low_m = min(float(elev["lowest"]["m"]), min(p[1] for p in profile)) + high_m = max(float(elev["highest"]["m"]), max(p[1] for p in profile)) + span = high_m - low_m + pad = max(10.0, span * 0.06) if span else 10.0 + y_lo = max(0.0, low_m - pad) if low_m >= 0 else low_m - pad + y_hi = high_m + pad + if y_hi <= y_lo: + y_hi = y_lo + 20 + + def x(dist_km): + return LEFT + dist_km / x_max * plot_w + + def y(elev_m): + return TOP + (y_hi - elev_m) / (y_hi - y_lo) * plot_h + + paths = [] + for seg in segments(profile, elev.get("part_starts_km")): + if len(seg) < 2: + continue + cmd = "M" + " L".join(f"{x(float(d)):.1f} {y(float(m)):.1f}" for d, m in seg) + paths.append(cmd) + line = f'' + + high_pt = max(profile, key=lambda p: p[1]) + low_pt = min(profile, key=lambda p: p[1]) + marks = "".join( + f'' + for d, m in (high_pt, low_pt)) + + def axis_group(system): + """Ticks, grid lines and axis titles for one unit system.""" + out = [] + if system == "km": + yticks, ystep = _ticks(y_lo, y_hi, 4) + yvals = [(t, t) for t in yticks] + xticks, xstep = _ticks(0, x_max, 5) + xvals = [(t, t) for t in xticks] + ytitle, xtitle = "Elevation (m)", "Distance along the track (km)" + else: + yticks, ystep = _ticks(y_lo / words.M_PER_FT, y_hi / words.M_PER_FT, 4) + yvals = [(t * words.M_PER_FT, t) for t in yticks] + xticks, xstep = _ticks(0, words.km_to_mi(x_max), 5) + xvals = [(t * words.KM_PER_MI, t) for t in xticks] + ytitle, xtitle = "Elevation (ft)", "Distance along the track (mi)" + for elev_m, label in yvals: + yy = y(elev_m) + if TOP - 1 <= yy <= TOP + plot_h + 1: + out.append(f'') + out.append(f'{esc(_fmt_tick(label, ystep))}') + for dist_km, label in xvals: + xx = x(dist_km) + if LEFT - 1 <= xx <= LEFT + plot_w + 1: + anchor = "start" if label == 0 else "middle" + out.append(f'{esc(_fmt_tick(label, xstep))}') + middle_y = TOP + plot_h / 2 + out.append(f'{esc(ytitle)}') + out.append(f'{esc(xtitle)}') + cls = "len__km" if system == "km" else "len__mi" + return f'{"".join(out)}' + + axes = (f'' + f'') + return Markup( + f'' + f"{axis_group('km')}{axis_group('mi')}{axes}{line}{marks}") diff --git a/web/olt/facets.py b/web/olt/facets.py new file mode 100644 index 0000000..ad9a8f0 --- /dev/null +++ b/web/olt/facets.py @@ -0,0 +1,310 @@ +"""The attributes a hiker sees for a trail, each with one name used on every page. + + Where the states and provinces, grouped into places (PLACE_GROUPS) + Length length_km + Time [hike].days as a source states it, else an estimate from the length + Season [hike].months (the phrase on the trail page is [hike].season) + Terrain [hike].terrain + Kind official trail, or route (the [route] table) + Walking [hike].travel + Shape [hike].shape + GPX one status per trail, from the track and, for a route, its author's terms + Designation National Scenic Trail (tier "national"), shown as a badge + +Every value here is computed from the records by rule. Nothing names a trail. +The dataset's own terms (tier, wave, source status, track policy) are not +attributes a hiker filters by; they stay in "About this data" on each trail +page and on the pages under About. +""" +import math + +from . import common, hike, words + +# Facet names, exactly as every page shows them. +WHERE, LENGTH, TIME, SEASON, TERRAIN, KIND, WALKING, SHAPE, GPX = ( + "Where", "Length", "Time", "Season", "Terrain", "Kind", "Walking", "Shape", "GPX") + +# A facet a trail may have no value for is offered as a filter only when at +# least this share of all trails has a value. +COVERAGE_MIN = 1 / 3 + +# Where ---------------------------------------------------------------------- + +# (key, name, [region keys]). Every state, province and territory code is in +# exactly one group (test_facets checks it against words.US_STATES and +# words.CA_PROVINCES, and against every code the records use). +PLACE_GROUPS = ( + ("west-coast", "West Coast", ["US-WA", "US-OR", "US-CA", "US-HI"]), + ("mountain-west", "Mountain West", ["US-ID", "US-MT", "US-WY", "US-NV", "US-UT", "US-CO"]), + ("southwest", "Southwest", ["US-AZ", "US-NM", "US-TX", "US-OK"]), + ("midwest", "Midwest", ["US-ND", "US-SD", "US-NE", "US-KS", "US-MN", "US-IA", "US-MO", + "US-WI", "US-IL", "US-MI", "US-IN", "US-OH"]), + ("south", "South", ["US-AR", "US-LA", "US-MS", "US-AL", "US-TN", "US-KY", "US-GA", + "US-FL", "US-SC", "US-NC"]), + ("mid-atlantic", "Mid-Atlantic", ["US-NY", "US-NJ", "US-PA", "US-DE", "US-MD", "US-DC", + "US-VA", "US-WV"]), + ("new-england", "New England", ["US-CT", "US-RI", "US-MA", "US-VT", "US-NH", "US-ME"]), + ("north", "Alaska and the North", ["US-AK", "CA-YT", "CA-NT", "CA-NU"]), + ("western-canada", "Western Canada", ["CA-BC", "CA-AB", "CA-SK", "CA-MB"]), + ("central-canada", "Central Canada", ["CA-ON", "CA-QC"]), + ("atlantic-canada", "Atlantic Canada", ["CA-NB", "CA-NS", "CA-PE", "CA-NL"]), +) +GROUP_OF = {key: g for g, _, keys in PLACE_GROUPS for key in keys} +GROUP_NAME = {g: name for g, name, _ in PLACE_GROUPS} +# A trail that names "all provinces and territories" crosses Canada: it is in +# every Canadian group, but on no single province's page. +ACROSS_CANADA = "CA-*" +ACROSS_CANADA_NAME = "Across Canada" + + +def place_keys(rec): + """The trail's states and provinces as keys ("US-AZ", "CA-ON", "CA-*"), in record order.""" + out = [] + for code in rec.get("regions", []): + key = words.region_key(code, rec["country"]) + if key not in out: + out.append(key) + return out + + +def place_groups(rec): + """The place groups a trail is in, in PLACE_GROUPS order.""" + keys = set(place_keys(rec)) + found = {GROUP_OF[k] for k in keys if k in GROUP_OF} + if ACROSS_CANADA in keys: + found |= {GROUP_OF[k] for k in GROUP_OF if k.startswith("CA-")} + return [g for g, _, _ in PLACE_GROUPS if g in found] + + +def place_name(key): + """"US-AZ" -> "Arizona"; "CA-*" -> "Across Canada".""" + if key == ACROSS_CANADA: + return ACROSS_CANADA_NAME + return words.region_name(key.split("-", 1)[1]) + + +def place_path(key): + """The page of a state or province (the /regions/ URLs are kept).""" + if key == ACROSS_CANADA: + return "/regions/#across-canada" + return f"/regions/{key.lower()}/" + + +def where_tokens(rec): + """Every Where value a trail matches: its countries, states and provinces, and groups.""" + return common.countries(rec) + place_keys(rec) + ["g:" + g for g in place_groups(rec)] + + +# Time ----------------------------------------------------------------------- + +PACE_KM = (20, 30) # km a day on trail +PACE_KM_CROSS = (12, 20) # km a day where much of it is cross-country +CROSS_COUNTRY = ("some-cross-country", "mostly-cross-country") + +# (key, label, most days). A trail falls in the band of the middle of its range. +TIME_BANDS = ( + ("week", "A week or less", 7), + ("two-weeks", "One to two weeks", 14), + ("month", "Two to four weeks", 28), + ("months", "One to three months", 91), + ("long", "More than three months", math.inf), +) +TIME_LABEL = {k: label for k, label, _ in TIME_BANDS} + + +def pace(rec): + return PACE_KM_CROSS if hike.table(rec).get("travel") in CROSS_COUNTRY else PACE_KM + + +def time_days(rec): + """(fewest, most, estimated): the days to walk it all. As a source states it in + [hike].days; otherwise estimated from the length at pace(rec) km a day.""" + stated = hike.table(rec).get("days") + if isinstance(stated, (int, float)): + stated = [stated] + stated = [d for d in (stated or []) if isinstance(d, (int, float)) and d > 0] + if stated: + return min(stated), max(stated), False + slow, fast = pace(rec) + km = rec["length_km"] + return max(1, math.ceil(km / fast)), max(1, math.ceil(km / slow)), True + + +def time_band(rec): + lo, hi, _ = time_days(rec) + mid = (lo + hi) / 2 + for key, _, most in TIME_BANDS: + if mid <= most: + return key + return TIME_BANDS[-1][0] + + +def time_text(rec): + """"5 to 7 months"; "About 2 to 3 weeks" when estimated.""" + lo, hi, est = time_days(rec) + text = words.fmt_days([lo, hi]) + if est and not text.startswith("about"): + text = "about " + text + return text[:1].upper() + text[1:] + + +def estimate_note(rec): + """Says how an estimated time was worked out; "" when a source states it.""" + if not time_days(rec)[2]: + return "" + slow, fast = pace(rec) + mi = f"{round(slow / words.KM_PER_MI)} to {round(fast / words.KM_PER_MI)} mi" + return f"Estimated from the length, at {slow} to {fast} km ({mi}) a day." + + +# Season --------------------------------------------------------------------- + +MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", + "September", "October", "November", "December") + + +def months(rec): + m = hike.table(rec).get("months") + return sorted({x for x in (m or []) if isinstance(x, int) and 1 <= x <= 12}) + + +def season_text(rec): + """The phrase on the trail page: [hike].season, else built from the months.""" + phrase = (hike.table(rec).get("season") or "").strip() + if phrase: + return phrase[:1].upper() + phrase[1:] + ms = months(rec) + if not ms: + return "" + if len(ms) == 12: + return "All year" + return words.join_names(MONTHS[m - 1] for m in ms) + + +# Terrain, Walking, Shape ---------------------------------------------------- + +TERRAIN_VALUES = words.TERRAIN +WALKING_VALUES = { + "trail": "On trail", + "trail-and-road": "Trail and road", + "some-cross-country": "Some cross-country", + "mostly-cross-country": "Mostly cross-country", +} +WALKING_HINT = { + "trail": "On built or maintained trail all or nearly all the way", + "trail-and-road": "Trail, with long stretches on roads", + "some-cross-country": "Mostly trail or road, with stretches that have no trail", + "mostly-cross-country": "No trail for most of the way", +} +SHAPES = {"point-to-point": "End to end", "loop": "Loop", "network": "Network"} + + +def terrain(rec): + return hike.terrain(rec) + + +def walking(rec): + v = hike.table(rec).get("travel", "") + return v if v in WALKING_VALUES else "" + + +def shape(rec): + v = hike.shape(rec) + return v if v in SHAPES else "" + + +# Kind ----------------------------------------------------------------------- + +KINDS = {"trail": "Official trail", "route": "Route"} +ROUTE_DEFINITION = ("A route is a trail that a hiker worked out and published. No agency or " + "association looks after it as one trail, and there may be no signs for it.") + + +def kind(rec): + return "route" if common.is_route(rec) else "trail" + + +def route_by(rec): + """"Route by Andrew Skurka, 2018"; "" for an official trail.""" + if not common.is_route(rec): + return "" + r = rec.get("route", {}) + who = r.get("creator", "") + if not who: + return "Route" + return f"Route by {who}" + (f", {r['year']}" if r.get("year") else "") + + +def author(rec): + return rec.get("route", {}).get("creator", "") if common.is_route(rec) else "" + + +def is_national(rec): + return rec.get("tier") == "national" + + +# GPX ------------------------------------------------------------------------ + +GPX_STATUS = { + "here": "GPX to download here", + "partial": "Partial GPX to download here", + "free": "Free from its author", + "sold": "Sold by its author", + "unpublished": "Not published", + "elsewhere": "Not here, see the official site", +} +# The short form in a list row. +GPX_SHORT = { + "here": "GPX here", + "partial": "Partial GPX here", + "free": "Free from its author", + "sold": "Sold by its author", + "unpublished": "Not published", + "elsewhere": "See the official site", +} + + +def gpx(rec): + """The trail's one GPX status (a key of GPX_STATUS).""" + if common.has_line(rec): + return "partial" if common.line_short(rec) else "here" + if common.is_route(rec): + return {"open": "free", "sold": "sold", "withheld": "unpublished"}.get(common.policy(rec), "elsewhere") + return "elsewhere" + + +def gpx_here(rec): + return gpx(rec) in ("here", "partial") + + +# Coverage ------------------------------------------------------------------- + +# facet key -> (name, the trail's values: a list, empty when it has none) +OPTIONAL = { + "season": (SEASON, months), + "terrain": (TERRAIN, terrain), + "walking": (WALKING, lambda r: [walking(r)] if walking(r) else []), + "shape": (SHAPE, lambda r: [shape(r)] if shape(r) else []), +} +# The noun for "12 trails have no ... on file". +MISSING_NOUN = {"season": "season", "terrain": "terrain", "walking": "walking", "shape": "shape"} + + +def coverage(records, key): + """(trails with a value, trails without) for an optional facet.""" + fn = OPTIONAL[key][1] + have = sum(1 for r in records if fn(r)) + return have, len(records) - have + + +def offered(records, key): + """True when the facet is offered as a filter: at least COVERAGE_MIN of trails have a value.""" + have, _ = coverage(records, key) + return bool(records) and have >= COVERAGE_MIN * len(records) + + +def missing_text(n, key): + """"12 trails have no season on file."; "" for none.""" + 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." diff --git a/web/olt/hike.py b/web/olt/hike.py new file mode 100644 index 0000000..56bd514 --- /dev/null +++ b/web/olt/hike.py @@ -0,0 +1,95 @@ +"""The hiker facts of a record: its optional [hike] table (docs/schema.md). + +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 re + +from . import words + +# Words after which a full stop does not end a sentence ("Mt. Rainier", "U.S. Forest Service"). +_ABBREVIATIONS = {"mt", "st", "ft", "dr", "mr", "mrs", "ms", "jr", "sr", "no", "vs", "ca", "approx", + "u.s", "e.g", "i.e", "etc", "hwy", "rd", "mi", "km"} +_SENTENCE_END = re.compile(r"[.!?](?=\s+[A-Z0-9“\"(])") + + +def table(rec): + value = rec.get("hike") + return value if isinstance(value, dict) else {} + + +def has(rec): + return bool(table(rec)) + + +def summary(rec): + return (table(rec).get("summary") or "").strip() + + +def first_sentence(text): + """The first sentence of a text: "A. B." -> "A.". Initials and common + abbreviations ("Mt.", "U.S.") do not end a sentence.""" + text = (text or "").strip() + for m in _SENTENCE_END.finditer(text): + word = re.search(r"([\w.]+)$", text[:m.start()]) + w = word.group(1).lower() if word else "" + if w in _ABBREVIATIONS or (len(w) == 1 and w.isalpha()): + continue + return text[:m.end()] + return text + + +def one_line(rec): + """The one-line description: the first sentence of the summary, or "".""" + return first_sentence(summary(rec)) + + +def days(rec): + return words.fmt_days(table(rec).get("days")) + + +def days_max(rec): + """The most days it usually takes, or None.""" + d = table(rec).get("days") + if isinstance(d, (int, float)): + d = [d] + d = [x for x in (d or []) if isinstance(x, (int, float)) and x > 0] + return max(d) if d else None + + +def shape(rec): + return table(rec).get("shape", "") + + +def terrain(rec): + return [t for t in table(rec).get("terrain", []) if t in words.TERRAIN] + + +def official_url(rec): + url = table(rec).get("official_url", "") + return url if isinstance(url, str) and url.startswith(("http://", "https://")) else "" + + +def ends(rec): + """(label, text) for where it starts and ends, or None. + + point-to-point (or no shape): "Start and end", "A to B"; loop: "Loop", "Starts and + ends at A"; network: "Network of trails", "Most walks start at A". + """ + h = table(rec) + start, end, sh = h.get("start", ""), h.get("end", ""), h.get("shape", "") + if sh == "loop": + return ("Loop", f"Starts and ends at {start}" if start else "Starts and ends at the same place") + if sh == "network": + return ("Network of trails", f"Usual start: {start}" if start else "Several ways to start and end") + if start and end: + return ("Start and end", (start, end)) + if start: + return ("Start", start) + if end: + return ("End", end) + return None + + +def sources(rec): + return [s for s in table(rec).get("source", []) if isinstance(s, dict)] diff --git a/web/olt/home.py b/web/olt/home.py index a01a17c..51dbf32 100644 --- a/web/olt/home.py +++ b/web/olt/home.py @@ -1,22 +1,23 @@ -"""The home page: what the site is, the overview map, and the trail finder with every record. +"""The home page: the catalogue. Search, the filters, and the trails as a list and on a map. -The list of records (results(), entry()) is shared with the region pages and -the routes page, so every list of records on the site looks and reads the same. +The list (results(), entry()) is shared with the place pages and the lists, so +every list of trails on the site looks and reads the same. The filters are the +attributes in olt/facets.py, under the same names the trail pages use. """ import collections import math import re -from . import common, words +from . import browse, common, elevation, facets, hike, words from .markup import Markup, esc # Length range choices (km) for the filters. length_steps() adds a top step -# above the longest record, so a chosen upper bound can always reach every record. +# above the longest trail, so a chosen upper bound can always reach every trail. LENGTH_STEPS = (60, 80, 100, 150, 200, 300, 500, 1000, 2000, 4000, 8000) def length_steps(records): - """LENGTH_STEPS plus a round step at or above the longest record, when that is longer.""" + """LENGTH_STEPS plus a round step at or above the longest trail, when that is longer.""" longest = max((r["length_km"] for r in records), default=0) steps = list(LENGTH_STEPS) if longest > steps[-1]: @@ -26,27 +27,31 @@ def length_steps(records): def counts(records): - """Counts for the filters. A record counts under each country it touches (its own - country and its regions' countries) and under each of its regions, as on /regions/; - a Canada-wide record counts under "region:CA-*", not under each province.""" + """Counts for the filter options: each Where value, Time band, month, terrain, Kind, + Walking, Shape and GPX status, as the filter would find them.""" c = collections.Counter() for r in records: c["total"] += 1 - c[common.kind(r)] += 1 - c["line" if common.has_line(r) else "record_only"] += 1 - if common.is_route(r): - c["route_line" if common.has_line(r) else "route_record_only"] += 1 - c["policy:" + common.policy(r)] += 1 - c["tier:" + r.get("tier", "")] += 1 - for country in common.countries(r): - c["country:" + country] += 1 - for key in set(words.region_key(code, r["country"]) for code in r.get("regions", [])): - c["region:" + key] += 1 + for tok in facets.where_tokens(r): + c["where:" + tok] += 1 + c["time:" + facets.time_band(r)] += 1 + for m in facets.months(r): + c[f"month:{m}"] += 1 + for t in facets.terrain(r): + c["terrain:" + t] += 1 + c["kind:" + facets.kind(r)] += 1 + if facets.walking(r): + c["walking:" + facets.walking(r)] += 1 + if facets.shape(r): + c["shape:" + facets.shape(r)] += 1 + c["gpx:" + facets.gpx(r)] += 1 + if facets.gpx_here(r): + c["gpx_here"] += 1 return c def overview_bbox(records): - """data-bbox attribute: the extent of every line, so the map opens on it before the data loads.""" + """data-bbox attribute: the extent of every track, so the map opens on it before the data loads.""" boxes = [r["derived"]["bbox"] for r in records if r["derived"].get("bbox")] if not boxes: return "" @@ -58,61 +63,95 @@ def sort_name(rec): return re.sub(r"^The ", "", rec["name"]).lower() -def entry(rec, *, level=3, extra=""): - """One record in a list. Its data-* attributes drive the filters in app.js. +# A row ------------------------------------------------------------------------ - level: the heading level of the record's name. extra: HTML placed last in the row. +def entry_desc(rec): + """The one-line description of a row: the [hike] summary's first sentence, else + the trail's designation (an official trail) or nothing (a route says who made it).""" + one = hike.one_line(rec) + if one: + return one + if facets.kind(rec) == "route": + return "" + return rec.get("designation", "") + + +def where_html(rec): + """The states and provinces of a row, each linked to its place page, and the country.""" + parts = [] + for key in facets.place_keys(rec): + name = facets.place_name(key) + text = esc(name) if key == facets.ACROSS_CANADA else \ + Markup(f'{esc(key.split("-", 1)[1])}') + parts.append(f'{text}') + country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec)) + return Markup(" ".join(parts) + f' {esc(country)}') + + +def gpx_cell(rec): + status = facets.gpx(rec) + route = facets.kind(rec) == "route" + if facets.gpx_here(rec): + swatch = common.SWATCH_ROUTE if route else common.SWATCH_LINE + partial = (f'

    {esc(common.partial_short_text(rec))}

    ' + if common.line_differs(rec) else "") + return (f'{swatch}{esc(facets.GPX_SHORT[status])}' + f'GPX and GeoJSON{partial}') + return f'{common.SWATCH_NONE}{esc(facets.GPX_SHORT[status])}' + + +def entry(rec, *, level=3, extra="", routes_list=False): + """One trail in a list. Its data-* attributes drive the filters in app.js. + + level: the heading level of the trail's name. extra: HTML placed last in the row. + routes_list: the Routes list, whose "By " headings already say what the + row's Route badge and "Route by" line would repeat; both are left out there. """ - route = common.is_route(rec) - if route: - r = rec["route"] - desc = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "") - elif rec.get("tier") == "national" and common.designated_year(rec): - desc = "Designated " + common.designated_year(rec) - else: - desc = rec.get("designation", "") - where = Markup(f'{common.regions_html(rec, linked=True)} ' - f'{esc(words.COUNTRIES.get(rec["country"], rec["country"]))}') - policy = common.policy_chip(common.policy(rec)) if route else "" - partial = common.line_differs(rec) - if common.has_line(rec): - partial_note = (f'

    {esc(common.partial_short_text(rec))}

    ' - if partial else "") - line = (f'{common.SWATCH_ROUTE if route else common.SWATCH_LINE}Track{policy}' - f'{partial_note}' - f'GeoJSON, GPX' - f'{esc(common.short_source(rec))} · {esc(common.licence_label(rec))}') - note = "" - else: - line = f'{common.SWATCH_NONE}Record only{policy}' - note = (f'\n

    Why there is no track: ' - f'{esc(common.absent_reason_short(rec))}

    ') - regions = " ".join(words.region_key(c, rec["country"]) for c in rec.get("regions", [])) - search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"]] - + ([rec["route"]["creator"]] if route else [])).lower() + route = facets.kind(rec) == "route" + 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" - data = (f' data-id="{esc(rec["id"])}" data-country="{esc(rec["country"])}"' - f' data-countries="{esc(" ".join(common.countries(rec)))}" data-regions="{esc(regions)}"' - f' data-km="{rec["length_km"]}" data-kind="{esc(common.kind(rec))}"' - f' data-line="{"yes" if common.has_line(rec) else "no"}"{' data-partial="yes"' if partial else ""}' - f' data-tier="{esc(rec.get("tier", ""))}"' - f' data-policy="{esc(common.policy(rec))}" data-name="{esc(sort_name(rec))}" data-search="{esc(search)}"') + 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 + data = { + "id": rec["id"], "where": " ".join(facets.where_tokens(rec)), "km": rec["length_km"], + "climb": elev["ascent_m"] if elev 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(), + } + attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items()) + if common.line_differs(rec): + attrs += ' data-partial="yes"' h = f"h{level}" - return f"""
  • + tag_html = common.badges(rec, route_tag=not routes_list) + kicker = f'\n

    {tag_html}

    ' if tag_html else "" + by = f'\n

    {esc(facets.route_by(rec))}

    ' if route and not routes_list else "" + 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 "" + return f"""
  • {common.plate(rec)} -
    -

    {common.tags(rec, with_policy=False)}

    - <{h} class="entry__name">{common.name(rec)} {esc(rec.get("short_name", ""))} -

    {esc(desc)}

    -

    {where}

    +
    {kicker} + <{h} class="entry__name">{common.name(rec)} {esc(rec.get("short_name", ""))}{by}{desc_html} +

    {where_html(rec)}

    Length
    {words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}
    -
    Track
    {line}
    -
    {note}{extra} +
    Time
    {time_html}
    +
    GPX
    {gpx_cell(rec)}
    {climb_html} + {extra}
  • """ +# The filters ------------------------------------------------------------------ + def _length_options(steps, selected_any_last): opts = [f'' for km in steps] @@ -121,97 +160,138 @@ def _length_options(steps, selected_any_last): return '' + "".join(opts[:-1]) -def region_options(c): - """The region filter: each state, province and territory a record names, with the - count its /regions/ page shows; the Canada-wide records under their own option.""" - groups = [] - for country, table in (("US", words.US_STATES), ("CA", words.CA_PROVINCES)): - opts = [] - if country == "CA" and c["region:CA-*"]: - key = words.region_key(words.ALL_CANADA, "CA") - opts.append(f'') - for code, name in sorted(table.items(), key=lambda kv: kv[1]): - n = c[f"region:{country}-{code}"] - if n: - opts.append(f'') - groups.append(f'{"".join(opts)}') - return "".join(groups) +def where_options(c): + """The Where filter: the two countries, then each place group with its states and provinces.""" + opts = [f''] + for code in ("US", "CA"): + if c["where:" + code]: + opts.append(f'') + for g, name, keys in facets.PLACE_GROUPS: + if not c["where:g:" + g]: + continue + inner = [f''] + for key in sorted(keys, key=facets.place_name): + if c["where:" + key]: + inner.append(f'') + opts.append(f'{"".join(inner)}') + if c["where:" + facets.ACROSS_CANADA]: + opts.append(f'') + return "".join(opts) -def finder_form(c, steps=LENGTH_STEPS): - tier_opts = "".join( - f'' - for t in ("national", "regional", "short", "deferred", "candidate") if c["tier:" + t]) - policy_opts = "".join( - f'' - for p in ("open", "sold", "withheld", "unclear") if c["policy:" + p]) +def _checks(name, items, c, prefix, hints=None): + """Checkboxes for a multi-choice facet: (value, label) items with their counts.""" + out = [] + for value, label in items: + n = c[f"{prefix}:{value}"] + if not n: + continue + hint = f'{esc(hints[value])}' if hints and hints.get(value) else "" + out.append(f'') + return "".join(out) + + +def _missing(records, key): + """The note under an optional facet: how many trails it leaves out while it is in use.""" + _, without = facets.coverage(records, key) + if not without: + return "" + return (f'') + + +def finder_form(records, c=None, steps=None): + """Search and the first-rank filters in view; Walking, Shape and GPX behind "More".""" + c = c or counts(records) + steps = steps or length_steps(records) + first, more = [], [] + first.append(f"""
    + + +
    """) + first.append(f"""
    + {facets.LENGTH} +
    + + + + + +
    +

    Any length.

    +
    """) + first.append(f"""
    + {facets.TIME} +
    {_checks("time", [(k, label) for k, label, _ in facets.TIME_BANDS], c, "time")}
    +

    To walk it all. Where no source says, it is estimated from the length.

    +
    """) + if facets.offered(records, "season"): + month_opts = "".join(f'' + for i, m in enumerate(facets.MONTHS, 1)) + first.append(f"""
    + + +

    Trails usually walked in that month.

    + {_missing(records, "season")} +
    """) + if facets.offered(records, "terrain"): + first.append(f"""
    + {facets.TERRAIN} +
    {_checks("terrain", facets.TERRAIN_VALUES.items(), c, "terrain")}
    + {_missing(records, "terrain")} +
    """) + first.append(f"""
    + {facets.KIND} +
    + + + +
    +

    What is a route?

    +
    """) + if facets.offered(records, "walking"): + more.append(f"""
    + {facets.WALKING} + {_checks("walking", facets.WALKING_VALUES.items(), c, "walking", facets.WALKING_HINT)} + {_missing(records, "walking")} +
    """) + if facets.offered(records, "shape"): + more.append(f"""
    + {facets.SHAPE} + {_checks("shape", facets.SHAPES.items(), c, "shape")} + {_missing(records, "shape")} +
    """) + more.append(f"""
    + {facets.GPX} + {_checks("gpx", facets.GPX_STATUS.items(), c, "gpx")} +
    """) return f"""
    - {key()} + {key(official=not only_routes)} {list_head()}{lists}{empty}
    """) +# A map of a selection is drawn only when it has at least this many tracks. +MAP_MIN = 3 + + +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"]] + 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.

    ') + 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.

    ') + ids_attr = "" if scope == "all" else f' data-ids="{esc(" ".join(ids))}"' + n = len(ids) + return Markup(f"""
    +
    + +
    +
    +
    +

    The map needs JavaScript. The list has every trail.

    +
    + +
    +
    +
      +
    • {common.SWATCH_LINE}Official trail
    • +
    • {common.SWATCH_ROUTE}Route
    • +
    +

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

    +
    +
    """) + + +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.""" + items = "".join( + f'
  • {esc(lst.title)} {len(recs)}
  • ' + for lst, recs in browse.shown(records) if not lst.key.startswith("terrain-")) + if not items: + return "" + return f"""""" + + def render(records, site): - """The home page body (HTML) for every record.""" + """The home page body (HTML).""" c = counts(records) recs = sorted(records, key=sort_name) total = c["total"] - lede = (f"A record for each of {total} long trails and routes, as a rule 50 miles (80 km) or more: " - "what it is, how long it is, who publishes it, and on what terms its track may be passed on. " - "Where the terms allow, download the track as GPX or GeoJSON.") + lede = (f"{total} long-distance trails in the United States and Canada. Narrow them by where they are, " + f"how long they take, when to walk them and what the country is like. " + f"{c['gpx_here']} have a GPX to download.") contribute = "" if site.repo_url: - contribute = (f'

    Something wrong, or a trail missing? ' + contribute = (f'

    Something wrong, or a trail missing? ' f'Report a problem or ' - f'suggest a trail; ' - f'the records are text files anyone can fix or add to.

    ') - return f"""
    + f'suggest a trail.

    ') + return f"""
    -

    A public dataset · United States and Canada

    -

    {esc(site.tagline)}

    +

    Find a long trail

    {lede}

    -

    This is a dataset, not a navigation product. Tracks vary in quality, some trails are unfinished, and some records have no track at all; each of those says why.

    - {contribute} -

    Find a trail

    -
    -
    -
    Records
    {total}
    -
    Designated trails
    {c["designated"]}
    - -
    {common.SWATCH_LINE}With a track
    {c["line"]}
    -
    {common.SWATCH_NONE}Records only
    {c["record_only"]}
    -
    - -
    + {lists_row(records)}
    -
    -
    -
    -

    Every track in the dataset

    -

    {c["line"]} tracks, simplified for display. Select a trail on the map for its name.

    -
    -
    -
    - -
    -
    -
    -

    The map needs JavaScript. The list below has every record.

    -
    - -
    -
    -
      -
    • {common.SWATCH_LINE}Designated trail
    • -
    • {common.SWATCH_ROUTE}Person-defined route
    • -
    -

    Tracks are simplified to about 750 m here; each keeps the credit and licence named on its page. Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.

    -
    -
    -
    -
    - -
    +
    -
    -

    Find a trail

    -

    Search, then narrow by country, region, length, kind and track

    +

    Every trail

    + {finder_form(records, c, length_steps(records))} +
    + {overview_map(records, "Map of the trails the filters leave", wide=True, scope="all")} + {results(recs, finder=True)} +
    +
    +

    Not for navigation: tracks vary in quality and some trails are unfinished. Check each trail’s own maps before you go.

    + {contribute}
    - {finder_form(c, length_steps(records))} - {results(recs, finder=True)}
    """ diff --git a/web/olt/layout.py b/web/olt/layout.py index 9f74ecd..ecad498 100644 --- a/web/olt/layout.py +++ b/web/olt/layout.py @@ -5,9 +5,9 @@ To add a page (see also docs in pages.py): from olt.layout import layout, page_head, write_page from olt.markup import esc - body = page_head("Regions", kicker="Browse", lede="Trails by state, province and territory.") + body = page_head("Places", lede="Trails by state and province.") body += f'
    ...{esc(some_text)}...
    ' - html = layout("Regions", body, path="/regions/", description="Long trails by region.") + html = layout("Places", body, path="/regions/", description="Long trails by place.") write_page(out_dir, "/regions/", html) `path` is the page's own site path; it sets the canonical link (when @@ -23,13 +23,14 @@ from .markup import Markup, attrs, esc, json_block NAV = ( ("Trails", "/"), - ("Regions", "/regions/"), - ("Routes", "/routes/"), - ("Sources", "/sources/"), - ("Logos", "/logos/"), + ("Places", "/regions/"), ("About", "/about/"), - ("Data", "/data/"), ) +# Pages with no header item of their own, and the item they sit under. The +# lists (Routes among them) are part of Trails; the dataset pages are part of +# About and are linked from the About hub and the footer. +NAV_PARENT = {"/trails/": "/", "/lists/": "/", "/routes/": "/", + "/sources/": "/about/", "/logos/": "/about/", "/data/": "/about/"} FONT_PRELOADS = ( "/assets/fonts/source-serif-4-latin.woff2", @@ -41,9 +42,11 @@ MAPLIBRE_JS = "/assets/vendor/maplibre-gl/maplibre-gl.js" def _current(path, href): """True when the nav item href is the section the page at path belongs to.""" - if href == "/": - return path == "/" or path.startswith("/trails/") - return path.startswith(href) + if href == "/" and path == "/": + return True + if any(path.startswith(p) and parent == href for p, parent in NAV_PARENT.items()): + return True + return href != "/" and path.startswith(href) def header(path, site): @@ -62,30 +65,32 @@ def header(path, site): def footer(site): report = "" if site.repo_url: - report = (f'
  • Report an error in a record
  • ' + report = (f'
  • Report a problem
  • ' f'
  • Suggest a trail
  • ' f'
  • Fix or add a trail
  • ') return Markup(f"""
    - Lengths + Units
    - - + +
    diff --git a/web/olt/pages.py b/web/olt/pages.py index 4c91d5b..d50e9e8 100644 --- a/web/olt/pages.py +++ b/web/olt/pages.py @@ -8,6 +8,9 @@ writes: /trails//index.html one page per record /trails//trail.toml the raw record; release.txt beside it where the trail has one /trails//shield-thumb.png the list-size copy of a PNG logo (olt/thumbs.py) + /regions/, /regions// Places: the hub and one page per state or province + /lists/, /lists// the lists shown today (olt/browse.py); /routes/ is the Routes list + /about/ and the pages under it: /data/, /data/schema/, /data/changelog/, /sources/, /logos/ /404.html not found Adding a page elsewhere (regions, sources, ...): build its body as HTML, @@ -18,7 +21,7 @@ import json import os import shutil -from . import docs, home, layout, regions, seo, site as site_settings, thumbs, trail +from . import browse, docs, home, layout, regions, seo, site as site_settings, thumbs, trail WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ASSETS_DIR = os.path.join(WEB_DIR, "assets") @@ -55,14 +58,14 @@ def copy_record_files(rec, out_dir, repo_root): def not_found_page(site): body = layout.page_head("Page not found", kicker="404", - lede="There is no page at this address. Search the trails and routes by name instead.") + lede="There is no page at this address. Search the trails by name instead.") body += """
    -

    Find a trail on the home page, or browse by region.

    +

    Find a trail on the home page, or browse by place.

    """ return layout.layout("Page not found", body, path="/404.html", site=site) @@ -78,7 +81,7 @@ def render_site(records, out_dir, repo_root, site=None): for rec in records: copy_record_files(rec, out_dir, repo_root) thumbs.prepare(rec, out_dir, repo_root) - title, description, body, needs_map = trail.render(rec, site) + title, description, body, needs_map = trail.render(rec, site, records) path = f"/trails/{rec['id']}/" layout.write_page(out_dir, path, layout.layout(title, body, path=path, description=description, maps=needs_map, site=site)) @@ -104,8 +107,19 @@ def render_site(records, out_dir, repo_root, site=None): path = f"/regions/{slug}/" region_paths.append(path) add(path, t, d, b, maps=needs_map) - t, d, b = regions.routes_page(records, site, repo_root) - add("/routes/", t, d, b) + list_paths = [] + shown = browse.shown(records) + for lst, recs in shown: + if lst.key == "routes": + continue # /routes/ below, built whether or not the list is shown + t, d, b, needs_map = regions.list_page(lst, recs, len(records), site) + path = browse.path(lst) + list_paths.append(path) + add(path, t, d, b, maps=needs_map) + t, d, b = regions.lists_index_page(records, site) + add("/lists/", t, d, b) + t, d, b, needs_map = regions.routes_page(records, site, repo_root) + add("/routes/", t, d, b, maps=needs_map) t, d, b = docs.sources_page(records, site, repo_root) add("/sources/", t, d, b) t, d, b = docs.logos_page(records, site, repo_root) @@ -119,6 +133,6 @@ def render_site(records, out_dir, repo_root, site=None): t, d, b = docs.changelog_page(site, repo_root) add("/data/changelog/", t, d, b) docs.copy_licences(out_dir, repo_root) - seo.write_seo_files(out_dir, seo.all_paths(records, region_paths), site) - print(f"pages written {pages}: {len(records)} trail pages, home, 404, regions, routes, docs") + seo.write_seo_files(out_dir, seo.all_paths(records, region_paths + ["/lists/"] + list_paths), site) + print(f"pages written {pages}: {len(records)} trail pages, home, 404, places, lists, about") return pages diff --git a/web/olt/records.py b/web/olt/records.py index 96c970d..b8007ad 100644 --- a/web/olt/records.py +++ b/web/olt/records.py @@ -2,6 +2,8 @@ import os import tomllib +from . import elevation + ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SHIELD_NAMES = ("shield.svg", "shield.png") @@ -50,6 +52,7 @@ def load_record(root, tid): "has_line": bool(rec.get("source", {}).get("line_file")), "length_mi": int(round(length_km / 1.609344)), "files": find_files(root, tid, rec), + "elevation": elevation.load_file(root, tid), "status": trail_status(rec), } return rec diff --git a/web/olt/regions.py b/web/olt/regions.py index e101853..d62639a 100644 --- a/web/olt/regions.py +++ b/web/olt/regions.py @@ -1,180 +1,137 @@ -"""Region pages (/regions/, /regions//) and the routes page (/routes/). +"""Places (/regions/, /regions//), lists (/lists/, /lists//) and +the Routes list (/routes/). -Both list records with home.results(), the same list the home page shows. +Every page lists trails with home.results(), the same rows the home page shows. +The section is called Places; its pages keep their /regions/ URLs. """ import collections -from . import common, docs, home, words +from . import browse, common, facets, home, words from .markup import Markup, esc -# The /regions/ anchor and the finder's region key for records that name all of Canada. -CANADA_WIDE_ID = "canada-wide" -CANADA_WIDE_KEY = words.region_key(words.ALL_CANADA, "CA") # "CA-*" - - -def region_country(code): - return words.region_country(code) if code != words.ALL_CANADA else "" - - -def region_slug(code, fallback_country=""): - return words.region_key(code, region_country(code) or fallback_country).lower() - - -def region_path(code, fallback_country=""): - return f"/regions/{region_slug(code, fallback_country)}/" - def collect_regions(records): - """slug -> {code, country, name, records}; plus Canada-wide records separately.""" + """slug -> {key, code, country, name, group, records} for every state and province a + trail names; plus the trails that name all of Canada, separately.""" by_slug = {} - canada_wide = [] + across = [] for r in records: - for code in r.get("regions", []): - if code == words.ALL_CANADA: - canada_wide.append(r) + for key in facets.place_keys(r): + if key == facets.ACROSS_CANADA: + across.append(r) continue - country = region_country(code) or r["country"] - slug = region_slug(code, r["country"]) - info = by_slug.setdefault(slug, {"code": code, "country": country, - "name": words.region_name(code), "records": []}) + slug = key.lower() + country, code = key.split("-", 1) + info = by_slug.setdefault(slug, {"key": key, "code": code, "country": country, + "name": facets.place_name(key), + "group": facets.GROUP_OF.get(key, ""), "records": []}) if all(x["id"] != r["id"] for x in info["records"]): info["records"].append(r) for info in by_slug.values(): info["records"].sort(key=home.sort_name) - canada_wide.sort(key=home.sort_name) - return by_slug, canada_wide + across.sort(key=home.sort_name) + return by_slug, across -def country_records(records, country): - """Every record that touches a country: listed on one of its region pages, or Canada-wide.""" - return [r for r in records if country in common.countries(r)] +def group_records(records, group): + return [r for r in records if group in facets.place_groups(r)] -def _bbox_attr(recs): - boxes = [r["derived"]["bbox"] for r in recs if r["derived"].get("bbox")] - if not boxes: - return "" - box = [min(b[0] for b in boxes), min(b[1] for b in boxes), - max(b[2] for b in boxes), max(b[3] for b in boxes)] - return f' data-bbox="{",".join(f"{v:.4f}" for v in box)}"' +def _gpx_count(recs): + return sum(1 for r in recs if facets.gpx_here(r)) -def _region_map(recs, title): - ids = [r["id"] for r in recs if "line" in r["derived"]["files"]] - if not ids: - return ('

    No downloadable track in this region yet, so there is ' - 'nothing to draw. The records below say why.

    ') - return f"""
    -
    - -
    -
    -

    The map needs JavaScript. The list below has every record.

    -
    - -
    -
    -
    • {common.SWATCH_LINE}Designated trail
    • -
    • {common.SWATCH_ROUTE}Person-defined route
    -

    {len(ids)} track{"s" if len(ids) != 1 else ""} in this region, simplified for display. Select a trail on the map for its name.

    -
    -
    """ +def _plural(n, word="trail"): + return f"{n} {word}{'' if n == 1 else 's'}" def regions_index_page(records, site): - by_slug, canada_wide = collect_regions(records) + """(title, description, body) for /regions/: the Places hub.""" + by_slug, across = collect_regions(records) blocks = "" - tally = '
    Records
    ' + str(len(records)) + '
    ' - for country in ("US", "CA"): - n_country = len(country_records(records, country)) - tally += (f'') - infos = sorted((i for i in by_slug.values() if i["country"] == country), - key=lambda i: i["name"].lower()) - rows = "" - for info in infos: - lines = sum(1 for r in info["records"] if common.has_line(r)) - rows += (f'{esc(info["name"])} ' - f'{esc(info["code"])}' - f'{len(info["records"])}{lines}') - extra = "" - if country == "CA" and canada_wide: - links = ", ".join(f'{common.name(r)}' for r in canada_wide) - extra = (f'

    All provinces and territories

    ' - f'

    These records name all provinces and territories rather than ' - f'one province, so they have no single region page and are not counted under each ' - f'province: {links}. Open in the trail finder.

    ') - unit = "state" if country == "US" else "province or territory, or all of them" - blocks += f"""

    {esc(words.COUNTRIES[country])}

    -

    {n_country} records name at least one {unit}. Each is counted once, whichever - country it is filed under.

    -
    - {rows}
    State, province or territoryRecordsWith a downloadable track
    {extra}
    """ + jump = [] + for g, name, keys in facets.PLACE_GROUPS: + infos = sorted((by_slug[k.lower()] for k in keys if k.lower() in by_slug), key=lambda i: i["name"]) + if not infos: + continue + recs = group_records(records, g) + jump.append(f'
  • {esc(name)} {len(recs)}
  • ') + rows = "".join( + f'
  • {esc(i["name"])}' + f'{_plural(len(i["records"]))}
  • ' + for i in infos) + blocks += f"""
    +

    {esc(name)}

    +

    {_plural(len(recs))}, {_gpx_count(recs)} with a GPX here. + See them with the filters

    +
      {rows}
    +
    """ + if across: + links = ", ".join(f'{common.name(r)}' for r in across) + jump.append(f'
  • {facets.ACROSS_CANADA_NAME} {len(across)}
  • ') + blocks += f"""
    +

    {facets.ACROSS_CANADA_NAME}

    +

    {_plural(len(across))} that {"crosses" if len(across) == 1 else "cross"} the whole country rather than one province: {links}. + {"It is" if len(across) == 1 else "They are"} counted in every Canadian group, and on no single province’s page.

    +
    """ + n_us = sum(1 for r in records if "US" in common.countries(r)) + n_ca = sum(1 for r in records if "CA" in common.countries(r)) body = f"""
    -

    Browse

    Regions

    -

    Every state, province and territory a record names. A record that - crosses several regions appears on each region's page, under the country that region belongs to.

    +

    Places

    +

    The {len(records)} trails by state and province, grouped into parts of the + United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one’s page.

    -
    {tally}
    -
    {blocks}
    """ - return "Regions", "Long trails by state, province and territory, with counts of records and tracks.", Markup(body) +
      {"".join(jump)}
    +
    {blocks}
    """ + return "Places", "Long trails by state and province, grouped into parts of the United States and Canada.", Markup(body) def region_page(slug, records, site): + """(title, description, body, needs_map) for /regions//: the trails in one state or province.""" by_slug, _ = collect_regions(records) info = by_slug[slug] recs = info["records"] - lines = sum(1 for r in recs if common.has_line(r)) - key = words.region_key(info["code"], info["country"]) - same = sorted((s for s, i in by_slug.items() if i["country"] == info["country"]), - key=lambda s: by_slug[s]["name"].lower()) - idx = same.index(slug) - neighbours = [] - if idx > 0: - p = by_slug[same[idx - 1]] - neighbours.append(f'← {esc(p["name"])}') - if idx + 1 < len(same): - n = by_slug[same[idx + 1]] - neighbours.append(f'{esc(n["name"])} →') - nav = " · ".join(neighbours) - with_line = (f'With a track' if lines else "With a track") + key = info["key"] + group = info["group"] + group_name = facets.GROUP_NAME.get(group, "") + country = words.COUNTRIES[info["country"]] + n_gpx = _gpx_count(recs) + crumbs = '
  • Places
  • ' + if group: + crumbs += f'
  • {esc(group_name)}
  • ' + siblings = [] + if group: + _, _, keys = next(x for x in facets.PLACE_GROUPS if x[0] == group) + for k in sorted(keys, key=facets.place_name): + if k != key and k.lower() in by_slug: + siblings.append(f'{esc(facets.place_name(k))}') + nav = (f'') if siblings else "" body = f"""
    - +
    -

    {esc(words.COUNTRIES[info["country"]])} · {esc(info["code"])}

    +

    {esc(group_name + " · " if group_name else "")}{esc(country)}

    {esc(info["name"])}

    -

    {len(recs)} record{"s" if len(recs) != 1 else ""}, {lines} with a downloadable track.

    +

    {_plural(len(recs))} in {esc(info["name"])}, {n_gpx} with a GPX here. + Narrow them with the filters.

    -
    Records
    {len(recs)}
    -
    {common.SWATCH_LINE}{with_line}
    {lines}
    -
    {common.SWATCH_NONE}Records only
    {len(recs) - lines}
    -
    -

    Tracks in {esc(info["name"])}

    Only tracks in this region are drawn.

    - {_region_map(recs, info["name"])} -
    -
    -

    Trails and routes in {esc(info["name"])}

    -

    Open these in the trail finder to search and filter them.

    +
    + {home.overview_map(recs, f"Map of the trails in {info['name']}")} {home.results(recs)} - + {nav}
    """ title = info["name"] - return title, f"{len(recs)} long trails and routes in {info['name']}, {words.COUNTRIES[info['country']]}.", Markup(body), bool(lines) + 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 def route_guides(rec): - """A route's guides, placed last in its list row on /routes/.""" + """A route's guides, compact, placed last in its row on /routes/.""" items = "" for g in rec.get("guide", []): access = g.get("access", "") - price = "" - if g.get("price"): - price = f' · {esc(g["price"])}' - if g.get("price_checked"): - price += f' (read {esc(g["price_checked"])})' + price = f' · {esc(g["price"])}' if g.get("price") else "" fmt = f' · {esc(g["format"])}' if g.get("format") else "" items += (f'
  • {esc(g.get("title", ""))}' f' {esc(words.ACCESS.get(access, access))}' @@ -185,36 +142,84 @@ def route_guides(rec): f'
      {items}
  • ') -def routes_page(records, site, repo_root): - """(title, description, body) for /routes/.""" - readme = docs.sections_map(docs.read_doc(repo_root, "README.md")) - inc = readme.get("Inclusion rule", "") - paras = [p for p in inc.split("\n\n") if "Person-defined rout" in p and "at the same 50-mile floor" in p] - bullets = [p for p in inc.split("\n\n") if "The creator sells" in p] - explainer = "\n\n".join(paras + bullets) or readme.get("Person-defined routes", "") - intro = docs.render_doc("## What a person-defined route is\n\n" + explainer, site) - - policy_items = "" - for key in ("open", "sold", "withheld", "unclear"): - lab, short, rule = words.POLICIES[key] - policy_items += f'
  • {common.policy_chip(key)}{esc(short)}. {esc(rule)}
  • ' - policies = Markup(f'
      {policy_items}
    ') - - routes = [r for r in records if common.is_route(r)] - by_creator = collections.defaultdict(list) +def routes_page(records, site, repo_root=None): + """(title, description, body, needs_map) for /routes/: the Routes list.""" + routes = [r for r in records if facets.kind(r) == "route"] + by_author = collections.defaultdict(list) for r in routes: - by_creator[r.get("route", {}).get("creator", "") or "Unknown"].append(r) - groups = [(esc(creator), sorted(by_creator[creator], key=home.sort_name), route_guides) - for creator in sorted(by_creator, key=str.lower)] - - body = f"""
    -

    Person-defined routes

    Routes

    -

    {len(routes)} routes worked out and published by a person or a small group.

    + by_author[facets.author(r) or "Author not named"].append(r) + groups = [(f"By {esc(a)}", sorted(by_author[a], key=home.sort_name), route_guides) + for a in sorted(by_author, key=str.lower)] + n_gpx = _gpx_count(routes) + body = f"""
    + +

    A list

    Routes

    +

    {esc(facets.ROUTE_DEFINITION)}

    -
    {intro}
    -

    The four track policies

    {policies} -

    See the routes in the trail finder, or read a route below.

    -

    Routes by creator

    -

    Each route links to its record; its guides link out to the creator's or publisher's page.

    -{home.results(groups=groups)}
    """ - return "Routes", f"{len(routes)} person-defined routes by creator, with track policies and guides.", Markup(body) +
    +
    +

    Every other trail on this site is an official trail. Being a route says who looks after it, not + how rough it is: some routes are on maintained trail all the way, and some official trails have + long road walks. The Walking line on each trail’s page says what the walking is.

    +

    {_plural(len(routes), "route")}, by {len(by_author)} authors. {n_gpx} {"has" if n_gpx == 1 else "have"} a GPX here; for the rest, + each route’s page says whether its author gives the track away, sells it, or does not publish it. + Narrow them with the filters.

    +
    +
    +
    + {home.overview_map(routes, "Map of the routes with a GPX here")} + {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 + + +def list_page(lst, recs, total, site): + """(title, description, body, needs_map) for /lists//.""" + n_gpx = _gpx_count(recs) + rule = (f"Lists are picked out by rule from each trail’s facts, so they change as trails are added " + f"or corrected. A list is shown when it has at least {browse.MIN_SIZE} trails and no more than " + f"{round(browse.MAX_SHARE * 100)}% of the {total}.") + body = f"""
    + +
    +

    A list

    +

    {esc(lst.title)}

    +

    {esc(lst.blurb)} {_plural(len(recs))}, {n_gpx} with a GPX here.

    +
    +
    +
    + {home.overview_map(recs, f"Map of the trails in the list {lst.title}")} + {home.results(recs)} +

    {rule}

    + +
    """ + return lst.title, f"{lst.title}: {lst.blurb}", Markup(body), n_gpx >= home.MAP_MIN + + +def lists_index_page(records, site): + """(title, description, body) for /lists/: every list shown today, with a few of its trails.""" + cards = [] + for lst, recs in browse.shown(records): + sample = "".join( + f'
  • {common.name(r)} ' + f'{words.length(r["length_km"], "short", r["derived"]["length_mi"])}
  • ' + for r in recs[:4]) + cards.append(f"""
  • +

    {esc(lst.title)} {len(recs)}

    +

    {esc(lst.blurb)}

    +
      {sample}
    +

    See all {len(recs)}: {esc(lst.title)}

    +
  • """) + body = f"""
    + +

    Lists

    +

    Ready-made selections of the {len(records)} trails, a way to start. Each is + picked out by rule from what each trail’s page says, so a list grows as trails are added.

    +
    +
      {"".join(cards)}
    +

    A list is shown when it has at least {browse.MIN_SIZE} trails and no more than +{round(browse.MAX_SHARE * 100)}% of all of them. To combine conditions, use the filters on the home page.

    """ + return "Lists", "Ready-made lists of long trails: National Scenic Trails, routes, loops, the longest and more.", Markup(body) diff --git a/web/olt/trail.py b/web/olt/trail.py index eb0ade8..a6687a0 100644 --- a/web/olt/trail.py +++ b/web/olt/trail.py @@ -8,7 +8,7 @@ import os import re import urllib.parse -from . import common, words +from . import common, elevation, facets, hike, words from .markup import Markup, esc EXTRACT_SOURCES = {"osm": "OpenStreetMap", "usfs": "USDA Forest Service", "nps": "National Park Service"} @@ -70,18 +70,15 @@ def restates_no_line(value): def region_names(rec): - """The regions for the title block, each linked to its region page.""" - regions = rec.get("regions", []) - if len(regions) <= 3: - parts = [] - for code_ in regions: - if code_ == words.ALL_CANADA: - href = "/regions/#canada-wide" - else: - href = f"/regions/{words.region_key(code_, rec['country']).lower()}/" - parts.append(f'{esc(words.region_name(code_))}') - return Markup(", ".join(parts)) - return common.regions_html(rec, linked=True) + """The states and provinces for the glance, each linked to its place page; codes when there are many.""" + keys = facets.place_keys(rec) + parts = [] + for key in keys: + name = facets.place_name(key) + text = esc(name) if len(keys) <= 3 or key == facets.ACROSS_CANADA else \ + Markup(f'{esc(key.split("-", 1)[1])}') + parts.append(f'{text}') + return Markup((", " if len(keys) <= 3 else " ").join(parts)) _ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)") @@ -96,66 +93,198 @@ def org_name(text): # Page head ------------------------------------------------------------------ +def kind_word(rec): + return "route" if common.is_route(rec) else "trail" + + +def place_text(rec): + """Where it is, for a sentence: "in Oregon, United States", "across 14 states of the + United States", "across 9 states and provinces of the United States and Canada".""" + codes = rec.get("regions", []) + countries = [words.COUNTRIES.get(c, c) for c in common.countries(rec)] or \ + [words.COUNTRIES.get(rec["country"], rec["country"])] + country = words.join_names(countries) + if words.ALL_CANADA in codes or not codes: + return f"across {country}" if words.ALL_CANADA in codes else f"in {country}" + if len(codes) > 3: + unit = {"United States": "states", "Canada": "provinces and territories"}.get(country, "states and provinces") + the = words.join_names(("the " + c) if c == "United States" else c for c in countries) + return f"across {len(codes)} {unit} of {the}" + return f"in {words.join_names(words.region_name(c) for c in codes)}, {country}" + + +def fallback_lede(rec): + """A one-sentence description built from the record, for a record without a [hike] summary.""" + length_html = words.length(rec["length_km"], "inline", rec["derived"]["length_mi"]) + return Markup(f"A {kind_word(rec)} of {length_html} {esc(place_text(rec))}.") + + +def lead_line(rec): + """Who made or designated it: "Route by Steve Roper, 1970", or the trail's designation.""" + if common.is_route(rec): + return facets.route_by(rec) + return rec.get("designation", "") + + +def route_definition(): + """What a route is, one tap away from the Kind line of a route's page (no script needed).""" + return Markup(f'
    What is a route?' + f'

    {esc(facets.ROUTE_DEFINITION)} Every route.

    ') + + +def official_link(rec): + """(url, label) of the trail's own page: the [hike] official site, else the + publisher's page for the trail, else a route's free guide; None when the record has none.""" + url = hike.official_url(rec) + if url: + return url, "Official site" + src = rec.get("source", {}) + if src.get("publisher_url"): + who = org_name(src.get("publisher", "")) + return src["publisher_url"], (f"{who} website" if who else "The trail's website") + if common.is_route(rec): + for g in rec.get("guide", []): + if g.get("url"): + return g["url"], "The route's guide" + return None + + def page_head(rec): route = common.is_route(rec) - country = words.COUNTRIES.get(rec["country"], rec["country"]) - crumbs = [f'
  • Trails
  • ', - f'
  • {esc(country)}
  • '] - if route: - crumbs.append('
  • Person-defined routes
  • ') + crumbs = ['
  • Places
  • '] + keys = facets.place_keys(rec) + groups = facets.place_groups(rec) + if keys and keys[0] in facets.GROUP_OF: + g = facets.GROUP_OF[keys[0]] + crumbs.append(f'
  • {esc(facets.GROUP_NAME[g])}
  • ') + crumbs.append(f'
  • {esc(facets.place_name(keys[0]))}
  • ') + elif groups: + crumbs.append(f'
  • {esc(facets.ACROSS_CANADA_NAME)}
  • ') crumbs.append(f'
  • {common.name(rec)}
  • ') - if route: - r = rec["route"] - lead = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "") - else: - lead = rec.get("designation", "") - sub = f'{esc(lead)} · {region_names(rec)}, {esc(country)}' has_plate = bool(common.shield_url(rec)) plate = common.plate(rec, size="lg", link=True, eager=True) if has_plate else "" + summary = hike.summary(rec) + lede = common.rich(summary) if summary else fallback_lede(rec) + actions = [] + official = official_link(rec) + if official: + actions.append(f'{esc(official[1])} {common.ICON_EXTERNAL}') + if rec["derived"].get("downloads"): + actions.append(f'{common.ICON_DOWNLOAD}Download the GPX') + else: + actions.append(f'GPX: {esc(facets.GPX_STATUS[facets.gpx(rec)])}') + tag_html = common.badges(rec) + kicker = f'

    {tag_html}

    ' if tag_html else "" + lead = lead_line(rec) + define = route_definition() if route else "" return f"""
    {plate}
    -

    {common.tags(rec)}

    + {kicker}

    {common.name(rec)} {esc(rec.get("short_name", ""))}

    -

    {sub}

    + {f'

    {common.rich(lead)}

    ' if lead else ""} + {define}
    - {tally(rec)} +

    {lede}

    +

    {"".join(actions)}

    """ -def tally(rec): - v = rec.get("verification", {}) - note = rec.get("length_note", "") - if note.replace(",", "") in (f"{rec['length_km']} km", f"{rec['length_km']} km published"): - note = "" # the note only repeats the number - items = [("Published length", words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]), note)] - if v.get("verified") and "measured_km" in v: - diff = v.get("difference_percent", 0) - items.append(("Measured track", words.length(v["measured_km"], "stack", measured=True), - f"{words.fmt_percent(diff)} against published")) +def glance_row(label, value, note="", wide=False): + note_html = f"{note if isinstance(note, Markup) else esc(note)}" if note else "" + value_html = value if isinstance(value, Markup) else esc(value) + return Markup(f'
    {esc(label)}
    ' + f'
    {value_html}{note_html}
    ') + + +def glance(rec): + """The hiker's facts at a glance, under the attribute names every page uses.""" + h = hike.table(rec) + rows = [glance_row(facets.LENGTH, words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]))] + rows.append(glance_row(facets.TIME, facets.time_text(rec), facets.estimate_note(rec))) + season = facets.season_text(rec) + if season: + rows.append(glance_row(facets.SEASON, season)) + if facets.walking(rec): + rows.append(glance_row(facets.WALKING, facets.WALKING_VALUES[facets.walking(rec)])) + elev = elevation.get(rec) + if h.get("high_point") or h.get("high_point_m"): + # A named, sourced high point is better than a computed number. + value = Markup(esc(h.get("high_point", ""))) + if h.get("high_point_m"): + value = Markup(f'{value}{"
    " if h.get("high_point") else ""}{words.elevation(h["high_point_m"])}') + rows.append(glance_row("High point", value)) + elif elev: + rows.append(glance_row("High point", words.elevation(elev["highest"]["m"]), + elevation.COMPUTED_NOTE)) + if elev: + low = elev["lowest"] + low_note = ("Sea level. " if elevation.is_sea_level(low) else "") + elevation.COMPUTED_NOTE + rows.append(glance_row("Low point", words.elevation(low["m"]), low_note)) + climb = Markup(str(words.elevation(elev["ascent_m"]))) + if elevation.show_descent(elev): + climb = Markup(f'{climb}
    Descent: {words.elevation(elev["descent_m"])}') + if facets.shape(rec) == "loop": + climb_note = elevation.COMPUTED_NOTE + else: + climb_note = f"Computed from the track, {elevation.direction_words(elev)}." + rows.append(glance_row("Climb", climb, climb_note)) + ends = hike.ends(rec) + if ends: + label, text = ends + if isinstance(text, tuple): + text = Markup(f'{esc(text[0])} to {esc(text[1])}') + if facets.shape(rec): + text = Markup(f'{esc(facets.SHAPES[facets.shape(rec)])}. {esc(text) if not isinstance(text, Markup) else text}') + label = facets.SHAPE + rows.append(glance_row(label, text, wide=True)) + elif facets.shape(rec): + rows.append(glance_row(facets.SHAPE, facets.SHAPES[facets.shape(rec)])) + terrain = facets.terrain(rec) + if terrain: + rows.append(glance_row(facets.TERRAIN, ", ".join(words.TERRAIN[t] for t in terrain), wide=True)) + if h.get("permit"): + rows.append(glance_row("Permits", common.sentence(h["permit"]), wide=True)) + country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec)) + rows.append(glance_row(facets.WHERE, Markup(f'{region_names(rec)}, {esc(country)}'), wide=True)) + status = facets.gpx(rec) + if facets.gpx_here(rec): + text = facets.GPX_STATUS[status] + value = Markup(f'{esc(text)}') if rec["derived"].get("downloads") else text + note = common.partial_short_text(rec) if common.line_differs(rec) else "" else: - items.append(("Measured track", Markup('Not measured'), - "No track was downloaded and measured")) - if common.has_line(rec): - text = "In the dataset, partial" if common.line_short(rec) else "In the dataset" - link = Markup(f'{esc(text)}') if rec["derived"].get("downloads") else text - items.append(("Track", link, "Licence: " + common.licence_label(rec))) - else: - items.append(("Track", "Record only", "The reason is given below")) - if common.is_route(rec): - p = common.policy(rec) - items.append(("Track policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p))) - else: - t = rec.get("tier", "") - items.append(("Tier", words.label(words.TIERS, t), words.meaning(words.TIERS, t))) - cells = "".join(f'
    {esc(a)}
    {esc(b)}{f"{esc(c)}" if c else ""}
    ' - for a, b, c in items) - return Markup(f'
    {cells}
    ') + value = Markup(f'{esc(facets.GPX_STATUS[status])}') + note = "" + rows.append(glance_row(facets.GPX, value, note, wide=True)) + halves = [i for i, r in enumerate(rows) if 'class="glance__wide"' not in r] + if len(halves) % 2: # an odd one out takes the full width rather than leave a gap beside it + i = halves[-1] + rows[i] = Markup(rows[i].replace("
    ", '
    ', 1)) + caution = "" + if h.get("caution"): + caution = f'

    Know before you go. {common.rich(common.sentence(h["caution"]))}

    ' + unfinished = "" + if h.get("unfinished"): + unfinished = f'

    Not finished. {common.rich(common.sentence(h["unfinished"]))}

    ' + missing = [name for name, have in ((facets.SEASON, season), (facets.TERRAIN, terrain), + (facets.WALKING, facets.walking(rec))) if not have] + pending = "" + if missing: + names = words.join_names([missing[0]] + [m.lower() for m in missing[1:]]) + verb = "is" if len(missing) == 1 else "are" + pending = f'

    {esc(names)} {verb} not on file for this trail yet.

    ' + elev_caveat = elevation.coverage_caveat(elev) if elev else "" + elev_note = f'

    {esc(elev_caveat)}

    ' if elev_caveat else "" + return f"""
    +

    At a glance

    +
    {"".join(rows)}
    + {unfinished}{caution}{elev_note}{pending} +
    """ # Map or empty frame --------------------------------------------------------- @@ -187,25 +316,65 @@ def map_figure(rec): """ +def elevation_figure(rec): + """The elevation profile under the map, drawn as SVG at build time. With too + many parts (olt/elevation.py) there is no line to draw in walking order, so + the section says that and states the figures instead.""" + elev = elevation.get(rec) + if not elev: + return "" + loop = facets.shape(rec) == "loop" + sentence = elevation.summary_sentence(elev, loop) + caveat = elevation.coverage_caveat(elev) + caveat_html = f'

    {esc(caveat)}

    ' if caveat else "" + if not elevation.show_profile(elev): + return f"""
    +

    Elevation profile

    +
    +

    {esc(elevation.parts_caveat(elev))}

    +

    {esc(sentence)}

    + {caveat_html} +
    +
    """ + parts = elev.get("parts") or 1 + breaks = (f" The line breaks where the track does: it has {parts} parts, and no climb " + "is counted across a gap.") if parts > 1 else "" + return f"""
    +

    Elevation profile

    +
    + {elevation.profile_svg(elev, loop)} +

    {esc(sentence)}{esc(breaks)}

    {caveat_html}
    +
    +
    """ + + def free_guides(rec): return [g for g in rec.get("guide", []) if g.get("access") == "free"] +ROUTE_NO_GPX = { + # GPX status -> (heading, what this site does about it) + "free": ("Get the GPX from its author", + "A GPX is included here only where the author's terms allow passing it on, or where " + "OpenStreetMap maps the route. Otherwise the author's own page is the place to get it."), + "sold": ("The author sells the route as a guide", + "No GPX is included here from any source, OpenStreetMap included, so the author's work is respected."), + "unpublished": ("The author does not publish a track", + "No GPX is included here from any source, OpenStreetMap included, so the author's choice is respected."), + "elsewhere": ("No GPX here", + "No GPX is included here until it is clear that the author allows it."), +} + + def empty_frame(rec): + """The map frame of a trail with no GPX here: why, and where to get one.""" src = rec["source"] reason = src.get("line_absent_reason", "") actions = [] + status = facets.gpx(rec) if common.is_route(rec): - p = common.policy(rec) - titles = { - "open": "Get the track from the creator", - "sold": "The track is sold as a guide", - "withheld": "The creator does not publish a track", - "unclear": "Whether the track may be shared is not settled", - } - title = titles.get(p, "No track in this dataset") - rule = words.POLICIES.get(p, ("", "", ""))[2] - if p == "open" and free_guides(rec): + title, rule = ROUTE_NO_GPX.get(status, ROUTE_NO_GPX["elsewhere"]) + if status == "free" and free_guides(rec): g = free_guides(rec)[0] actions.append(f'' f'{esc(g["title"])} {common.ICON_EXTERNAL}') @@ -214,31 +383,42 @@ def empty_frame(rec): elif len(rec.get("guide", [])) > 1: actions.append('All guides') else: - title = "No track in this dataset" + title = "No GPX here" reason = common.absent_reason_short(rec) - rule = "A trail may be listed as a record only, with no track, when no track for it may be shared. The record says why." - if src.get("publisher_url"): - actions.append(f'' - f'Publisher’s page {common.ICON_EXTERNAL}') - elif src.get("url"): + rule = "A trail is listed without a GPX when no track for it may be passed on." + official = official_link(rec) + if official: + actions.append(f'' + f'{esc(official[1])} {common.ICON_EXTERNAL}') + places = [official[1][:1].lower() + official[1][1:] if official[1] == "Official site" + else "the " + official[1]] if official else [] + if src.get("url") and (not official or src["url"] != official[0]): + osm = host(src["url"]).endswith("openstreetmap.org") + label = "See it on OpenStreetMap" if osm else "Where to ask for the track" + places.append("OpenStreetMap, where the trail is mapped" if osm else "the track's source") actions.append(f'' - f'The source {common.ICON_EXTERNAL}') + f'{esc(label)} {common.ICON_EXTERNAL}') + if places: + places[0] = places[0].replace("official site", "the official site") + lead = f"For a track, try {words.join_names(places)}." + reason = Markup(f'{esc(lead)}

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

    {"".join(actions)}

    ' if actions else "" - return f"""
    + return f"""
    - +
    -

    Record only

    +

    GPX: {esc(facets.GPX_STATUS[status])}

    {esc(title)}

    -

    {common.rich(reason)}

    +

    {reason if isinstance(reason, Markup) else common.rich(reason)}

    {esc(rule)}

    {actions_html}
    -

    No map is drawn: the dataset holds no track for this {"route" if common.is_route(rec) else "trail"}, and does not guess one.

    +

    No map is drawn: there is no track for this trail here, and the site does not guess one.

    """ @@ -368,7 +548,7 @@ def guides_panel(rec):

    Where to get the route

      {cards}
    -

    Links go to the creator’s or publisher’s own page for each guide.

    +

    Links go to the author’s or publisher’s own page for each guide.

    """ @@ -377,7 +557,7 @@ def _is_url(value): return isinstance(value, str) and value.startswith(("http://", "https://")) -def links_panel(rec): +def links_block(rec): """Every link the record holds, each titled with the organisation or person the record names for it, with the host name and what the link is as secondary text.""" src = rec["source"] @@ -424,10 +604,7 @@ def links_panel(rec): return f"{host(url)} · {text}" if _is_url(url) else text lis = "".join(f'
  • {ext_link(u, t)}{esc(describe(u, w))}
  • ' for u, (t, w) in items.items()) - return f"""
    - -
    -
    """ + return block("links-title", "Links", Markup(f'')) # Main column ---------------------------------------------------------------- @@ -439,14 +616,14 @@ def policy_scale(current): here = ' aria-current="true"' if p == current else "" mark = 'This route' if p == current else "" items.append(f'{common.policy_chip(p)}{esc(short)}. {esc(rule)}{mark}') - return Markup(f'
      {"".join(items)}
    ') + return Markup(f'
      {"".join(items)}
    ') def route_block(rec): r = rec["route"] p = r.get("line_policy", "") rows = [ - fact("Creator", r.get("creator", "")), + fact("Author", r.get("creator", ""), "Who worked the route out (route.creator)"), fact("First published", str(r["year"])) if r.get("year") else fact("First published", "Not recorded", "No page read states a year"), fact("Track policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p)), @@ -454,8 +631,8 @@ def route_block(rec): quote = "" if r.get("creator_words"): by = r.get("creator_words_by") or r.get("creator", "") - not_creator = ('Not the creator’s words' - if r.get("creator_words_by") else 'The creator’s words') + not_creator = ('Not the author’s words' + if r.get("creator_words_by") else 'The author’s words') url = r.get("creator_words_url", "") quote = f"""

    {esc(r["creator_words"])}

    @@ -488,7 +665,9 @@ def record_block(rec): country = words.COUNTRIES.get(rec["country"], rec["country"]) names = ", ".join(words.region_name(c) for c in rec.get("regions", []) if c != words.ALL_CANADA) names_html = f' ({esc(names)})' if names else "" - where = Markup(f'{common.regions_html(rec, linked=True)}{names_html}, {esc(country)}') + codes = Markup(" ".join(f'{esc(k.split("-", 1)[1] if k != facets.ACROSS_CANADA else facets.ACROSS_CANADA_NAME)}' + for k in facets.place_keys(rec))) + where = Markup(f'{codes}{names_html}, {esc(country)}') rows = [ fact("Kind", words.label(words.KINDS, k), words.meaning(words.KINDS, k)), fact("Designation", rec.get("designation", "")), @@ -564,6 +743,85 @@ def verification_block(rec): return block("verify-title", "Verification", rows + record_text(v.get("note", "")) + Markup(gap_html)) +def _coord(point): + lat, lon = point.get("lat"), point.get("lon") + if isinstance(lat, (int, float)) and isinstance(lon, (int, float)): + return f"At {lat:.5f}, {lon:.5f} (latitude, longitude)" + return "" + + +def _fmt_number(value): + if isinstance(value, float) and value.is_integer(): + return f"{int(value):,}" + return f"{value:,}" if isinstance(value, (int, float)) else str(value) + + +def elevation_block(rec): + """How the elevation figures were computed, the model's credit, and every value.""" + elev = elevation.get(rec) + if not elev: + return "" + src = elev.get("source") or {} + model = src.get("model", "") + loop = facets.shape(rec) == "loop" + direction = elevation.direction_words(elev) + climb_note = elevation.COMPUTED_NOTE if loop else \ + f"Computed from the track, {direction}. Walking the other way swaps climb and descent." + low_note = _coord(elev["lowest"]) + if elevation.is_sea_level(elev["lowest"]): + low_note = ("Sea level. " + low_note).strip() + coverage = elev.get("coverage") + coverage_text = (f"{coverage:.3f} ({elevation.coverage_percent(elev)} of the published length)" + if isinstance(coverage, (int, float)) else str(coverage)) + starts = elev.get("part_starts_km") or [] + rows = [ + fact("Highest point on the track", words.elevation(elev["highest"]["m"]), _coord(elev["highest"])), + fact("Lowest point on the track", words.elevation(elev["lowest"]["m"]), low_note), + fact("Total climb", words.elevation(elev["ascent_m"]), climb_note), + fact("Total descent", words.elevation(elev["descent_m"]), climb_note), + fact("Length sampled", words.length(elev["track_km"], "inline", measured=True), + "The length of the track, not the published length"), + fact("Published length", words.length(elev["published_km"], "inline")), + fact("Coverage", coverage_text, elevation.coverage_caveat(elev) or + "Length sampled divided by the published length"), + fact("Parts", str(elev.get("parts", "")), + "Pieces left after joining track ends within 100 m, counted for the elevation sampling. " + "It can differ from the count under Verification, which was made with another joining rule. " + "No climb is counted across a gap."), + ] + if starts: + rows.append(fact("Part starts", ", ".join(words.fmt_km1(s) for s in starts) + " km", + "The distance along the profile where each part after the first begins")) + if not elevation.show_profile(elev): + rows.append(fact("Profile", "Not drawn", elevation.parts_caveat(elev))) + rows += [ + fact("Elevation model", model) if model else "", + Markup(f'
    Model page
    {ext_link(src["url"])}
    ') if src.get("url") else "", + fact("Model credit", src.get("attribution", ""), "The credit to show, as the model gives it") + if src.get("attribution") else "", + fact("Tiles", f"Zoom {_fmt_number(src['zoom'])}, about {_fmt_number(src['ground_m_per_pixel_at_40n'])} m " + "per cell at 40 degrees north") + if src.get("zoom") is not None and src.get("ground_m_per_pixel_at_40n") is not None else "", + fact("Sampling", f"Every {_fmt_number(src['sample_spacing_m'])} m along the track") + if src.get("sample_spacing_m") is not None else "", + fact("Smoothing", src.get("smoothing", "")) if src.get("smoothing") else "", + fact("Computed", str(src["computed"])) if src.get("computed") else "", + fact("Method version", str(src["method_version"])) if src.get("method_version") is not None else "", + ] + spacing = src.get("sample_spacing_m") + sampled = (f"A point was taken every {_fmt_number(spacing)} m along each part of the track, " + "and its elevation was read from the model. ") if spacing is not None else "" + smoothing = src.get("smoothing", "") + method = (f"These figures were computed from the trail’s track and {esc(model)}, " + f"not read from a page about the trail. {esc(sampled)}" + + (f"Smoothing and counting: {esc(smoothing.rstrip('.').lower()[:1] + smoothing.rstrip('.')[1:])}." + if smoothing else "")) + limits = src.get("limits", "") + limits_html = (f'

    Limits

    {record_text(limits)}') if limits else "" + content = Markup(f'

    {method}

    ') + facts(*rows) + Markup(limits_html) + return block("elevation-data-title", "Elevation", content) + + def source_block(rec): src = rec["source"] line = common.has_line(rec) @@ -660,7 +918,7 @@ def correction_block(rec, site): if common.is_route(rec): parts.append(f"""

    If you made this route

    -

    A route’s creator can ask for its record to be corrected or removed, and the record will be corrected or removed. Say which route: {code(rec["id"])}. See About.

    +

    The author of a route can ask for its record to be corrected or removed, and the record will be corrected or removed. Say which route: {code(rec["id"])}. See About.

    """) if site.is_github: report = esc(site.correction_url(rec["id"], rec.get("name", ""))) @@ -679,6 +937,50 @@ def correction_block(rec, site): return block("correct-title", "Corrections", Markup("".join(parts))) +def hike_sources_block(rec): + """Where the hiker facts at the top of the page were read.""" + h = hike.table(rec) + if not h: + return "" + items = "" + for src in hike.sources(rec): + url = src.get("url", "") + who = src.get("publisher") or (host(url) if url else "Source") + facts_ = [words.HIKE_FACTS.get(f, f) for f in src.get("facts", [])] + what = ("For " + words.join_names(facts_)) if facts_ else "" + link = ext_link(url, who) if url else esc(who) + detail = " · ".join(x for x in (host(url) if url else "", what) if x) + items += f"
  • {link}{f'{esc(detail)}' if detail else ''}
  • " + body = f'' if items else \ + '

    The record names no page for these facts.

    ' + checked = f'

    Checked {esc(h["checked"])}.

    ' if h.get("checked") else "" + return block("hike-title", "Where the hiking facts come from", Markup(body + checked)) + + +def about_data(rec, site): + """Everything about where the page's data comes from: collapsed, below the hiker's part.""" + blocks = ((route_block(rec) if common.is_route(rec) else "") + record_block(rec) + hike_sources_block(rec) + + verification_block(rec) + elevation_block(rec) + source_block(rec) + osm_block(rec) + logo_block(rec) + + links_block(rec) + correction_block(rec, site) + raw_record(rec)) + return f"""
    +

    About this data

    + Where the track and the facts come from, licence, checks, the logo, corrections, and every field of the record
    +
    + {blocks} +
    +
    """ + + +def page_foot(rec, site): + """The plain lines under the hiker's part: not for navigation, and how to report a problem.""" + report = "" + if site.repo_url: + report = (f' Something wrong on this page? ' + f'Report a problem.') + return (f'

    Not for navigation: check the trail’s own maps ' + f'and current conditions before you go.{report}

    ') + + def flatten(obj, prefix=""): """(field, value) for every leaf of a record: "source.licence", "guide[0].title", "regions[1]".""" if isinstance(obj, dict): @@ -719,35 +1021,82 @@ def raw_record(rec): # The page ------------------------------------------------------------------- def description(rec): - km = words.fmt_km(rec["length_km"]) - mi = words.fmt_int(rec["derived"]["length_mi"]) - where = ", ".join(words.region_name(c) for c in rec.get("regions", [])[:3]) - if len(rec.get("regions", [])) > 3: - where += " and more" - kind = "person-defined route" if common.is_route(rec) else "long trail" - text = f"{rec['name']}: a {km} km ({mi} mi) {kind} in {where}. " - if common.has_line(rec): - text += "Download its track as GPX or GeoJSON, with the source, licence and credit." + one = hike.one_line(rec) + if one: + text = one else: - text += "Record only: " + common.absent_reason_short(rec) + km = words.fmt_km(rec["length_km"]) + mi = words.fmt_int(rec["derived"]["length_mi"]) + text = f"{rec['name']}: a {kind_word(rec)} of {km} km ({mi} mi) {place_text(rec)}." + text += (" Download its GPX here." if common.has_line(rec) + else " Where to get its GPX.") return text if len(text) <= 300 else text[:297].rsplit(" ", 1)[0] + "…" -def render(rec, site): - """Return (title, description, body HTML, needs_map) for one record.""" +# Ways onward ------------------------------------------------------------------ + +ONWARD_MAX = 6 + + +def _onward_list(title, recs, more_href, more_text, heading_id): + items = "".join( + f'
  • {common.name(r)}' + f'{words.length(r["length_km"], "short", r["derived"]["length_mi"])}' + f'{" · Route" if common.is_route(r) else ""}
  • ' + for r in recs[:ONWARD_MAX]) + more = (f'

    {esc(more_text)}

    ' + if more_href else "") + return (f'
    ' + f'

    {esc(title)}

      {items}
    {more}
    ') + + +def onward(rec, records): + """Ways onward at the foot of the page: other trails in the same state or province + (up to three of them), and for a route, other routes by the same author.""" + if not records: + return "" + others = [r for r in records if r["id"] != rec["id"]] + parts = [] + for i, key in enumerate(k for k in facets.place_keys(rec) if k != facets.ACROSS_CANADA): + if i >= 3: + break + here = sorted((r for r in others if key in facets.place_keys(r)), key=lambda r: -r["length_km"]) + if not here: + continue + name = facets.place_name(key) + more = (facets.place_path(key), f"All {len(here) + 1} trails in {name}") if len(here) > ONWARD_MAX else \ + (facets.place_path(key), f"{name} on the map") + parts.append(_onward_list(f"More in {name}", here, more[0], more[1], f"onward-{key.lower()}")) + who = facets.author(rec) + if who: + same = sorted((r for r in others if facets.author(r) == who), key=lambda r: -r["length_km"]) + if same: + parts.append(_onward_list(f"More routes by {who}", same, "/routes/", "Every route", "onward-author")) + if not parts: + return "" + return (f'') + + +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) - aside = downloads_panel(rec) + guides_panel(rec) + links_panel(rec) - main = (route_block(rec) if common.is_route(rec) else "") + record_block(rec) + verification_block(rec) \ - + source_block(rec) + osm_block(rec) + logo_block(rec) + correction_block(rec, site) + raw_record(rec) + aside = downloads_panel(rec) + guides_panel(rec) + aside_html = (f'') if aside else "" + profile = elevation_figure(rec) body = f"""{page_head(rec)} -
    +
    + {glance(rec)} {map_figure(rec) if has_map else empty_frame(rec)} - -
    - {main} -
    + {profile} + {aside_html} +
    +
    + {onward(rec, records)} + {page_foot(rec, site)} + {about_data(rec, site)}
    """ return rec["name"], description(rec), body, has_map diff --git a/web/olt/words.py b/web/olt/words.py index e46c69d..5f3c33a 100644 --- a/web/olt/words.py +++ b/web/olt/words.py @@ -47,10 +47,11 @@ INCLUSION = { "candidate-decision-pending": ("Candidate", "The decision to list it is pending"), } KINDS = { - "designated": ("Designated trail", - "Designated, maintained and published as one trail by a land agency or a trail association"), - "route": ("Person-defined route", - "Worked out and published by a person or a small group: a high route, a traverse or a loop of linked trails"), + "designated": ("Official trail", + "Looked after as one trail by a land agency or a trail association"), + "route": ("Route", + "A trail that a hiker worked out and published. No agency or association looks after it " + "as one trail, and there may be no signs for it"), } SOURCE_STATUS = { "verified": ("Verified", "The track was downloaded from the source and measured"), @@ -75,14 +76,14 @@ LICENCE_URLS = { "CC-BY-NC-ND-4.0": "https://creativecommons.org/licenses/by-nc-nd/4.0/", } POLICIES = { - "open": ("Open", "The creator publishes the track freely", - "A track is included only where the creator's terms allow passing it on, or where " - "OpenStreetMap carries the route as a route relation. Otherwise get it from the creator."), + "open": ("Open", "The author publishes the track freely", + "A track is included only where the author's terms allow passing it on, or where " + "OpenStreetMap carries the route as a route relation. Otherwise get it from the author."), "sold": ("Sold", "The route is got by buying a guide or map set", "No track is included from any source, OpenStreetMap included."), - "withheld": ("Withheld", "The creator chooses not to publish a track", + "withheld": ("Withheld", "The author chooses not to publish a track", "No track is included from any source, OpenStreetMap included."), - "unclear": ("Unclear", "Whether the creator shares the track is not settled", + "unclear": ("Unclear", "Whether the author shares the track is not settled", "No track is included until it is settled."), } SHIELD_STATUS = { @@ -179,3 +180,65 @@ def length(km, style="inline", mi=None, measured=False): mi_text = f"{fmt_int(mi)} mi" if whole or mi >= 100 else f"{mi:,.1f} mi" return Markup(f'{esc(km_text)}' f'{esc(mi_text)}') + + +# Hiker facts ([hike] table) ------------------------------------------------- + +M_PER_FT = 0.3048 + +TERRAIN = { + "alpine": "Alpine", "forest": "Forest", "desert": "Desert", "coast": "Coast", + "prairie": "Prairie", "canyon": "Canyon", "tundra": "Tundra", "lakes": "Lakes", + "farmland": "Farmland", +} +# The [hike] fields a [[hike.source]] may name in `facts`, in plain words. +HIKE_FACTS = { + "summary": "description", "official_url": "official site", "start": "start", "end": "end", + "shape": "shape", "days": "time", "season": "season", "months": "season", "travel": "walking", "high_point": "high point", + "high_point_m": "high point elevation", "terrain": "terrain", "permit": "permits", + "unfinished": "unfinished sections", "caution": "caution", +} + +def _plural(n, unit): + return f"{n} {unit}" if n == 1 else f"{n} {unit}s" + + +def fmt_days(days): + """Usual time to walk a trail in one go, in a unit a person would use. + + [4, 6] -> "4 to 6 days"; [14, 21] -> "2 to 3 weeks"; [150, 210] -> "5 to 7 months". + Days up to 14, weeks up to 9 weeks (63 days), months beyond. One value, or both + ends the same after rounding: "5 days", "about 3 weeks". "" for no value. + """ + if isinstance(days, (int, float)): + days = [days] + days = [d for d in (days or []) if isinstance(d, (int, float)) and d > 0] + if not days: + return "" + lo, hi = min(days), max(days) + if hi <= 14: + unit, a, b = "day", round(lo), round(hi) + elif hi <= 63: + unit, a, b = "week", max(1, round(lo / 7)), max(1, round(hi / 7)) + else: + unit, a, b = "month", max(1, round(lo / 30.44)), max(1, round(hi / 30.44)) + if a == b: + return _plural(a, unit) if unit == "day" else "about " + _plural(a, unit) + return f"{a} to {b} {unit}s" + + +def elevation(m, style="inline"): + """An elevation in metres and feet; the reader's unit preference decides the order, + with the same len__km / len__mi pair as lengths: "2,025 m (6,644 ft)". + style "stack" sets the first unit large over the second, as lengths do.""" + ft = m / M_PER_FT + return Markup(f'{esc(fmt_int(m))} m' + f'{esc(fmt_int(ft))} ft') + + +def join_names(names): + """["a"] -> "a"; ["a", "b"] -> "a and b"; ["a", "b", "c"] -> "a, b and c".""" + names = list(names) + if len(names) <= 1: + return "".join(names) + return ", ".join(names[:-1]) + " and " + names[-1] diff --git a/web/serve.py b/web/serve.py index c19cb30..230ed0d 100644 --- a/web/serve.py +++ b/web/serve.py @@ -4,7 +4,7 @@ For checking pages under the production Content-Security-Policy (Netlify applies _headers in production; plain `python3 -m http.server` does not). - python3 web/serve.py [--dir _site] [--port 8000] + python3 web/serve.py [--dir _site] [--port 8000] [--bind 127.0.0.1] """ import argparse import functools @@ -74,11 +74,13 @@ def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--dir", default=os.path.join(root, "_site")) ap.add_argument("--port", type=int, default=8000) + ap.add_argument("--bind", default="127.0.0.1", + help="address to listen on; 0.0.0.0 lets other devices on the network reach it") args = ap.parse_args() Handler.rules = parse_headers(os.path.join(args.dir, "_headers")) handler = functools.partial(Handler, directory=args.dir) - with http.server.ThreadingHTTPServer(("127.0.0.1", args.port), handler) as httpd: - print(f"serving {args.dir} at http://127.0.0.1:{args.port}/ with {len(Handler.rules)} header rules") + with http.server.ThreadingHTTPServer((args.bind, args.port), handler) as httpd: + print(f"serving {args.dir} at http://{args.bind}:{args.port}/ with {len(Handler.rules)} header rules") httpd.serve_forever() diff --git a/web/tests/test_elevation.py b/web/tests/test_elevation.py new file mode 100644 index 0000000..4c20692 --- /dev/null +++ b/web/tests/test_elevation.py @@ -0,0 +1,284 @@ +"""Tests for the computed elevation facts (olt/elevation.py): the At a glance +rows, the profile and its part breaks, the caveats, unit switching, the climb +sort, the model credit, and the Routes list dropping its repetition. + +These render fixtures; they do not need the built site. +""" +import copy +import html +import os +import re +import sys +import unittest + +WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +ROOT = os.path.dirname(WEB) +sys.path.insert(0, WEB) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from olt import docs, elevation, home, records, regions, site, trail # noqa: E402 +from test_pages import sample_record # noqa: E402 + +GH = site.Site("N", "T", repo_url="https://github.com/o/r") + +SOURCE = { + "model": "Example Model", "url": "https://model.example/", + "attribution": "Example Model credit, as it gives it.", + "zoom": 12, "ground_m_per_pixel_at_40n": 29.2, "sample_spacing_m": 30.0, + "smoothing": "Moving average over 90 m of track; ascent and descent counted with a 5 m reversal threshold", + "limits": "Computed from a public elevation model, not measured on the ground.", + "method_version": 1, "computed": "2026-11-13", +} + + +def elev(**kw): + """A small elevation.json in memory: one part, full coverage, south to north.""" + data = { + "highest": {"m": 2000, "lat": 40.0, "lon": -105.0}, + "lowest": {"m": 500, "lat": 39.0, "lon": -105.5}, + "ascent_m": 3000, "descent_m": 2900, + "track_km": 100.0, "published_km": 100, "coverage": 1.0, + "parts": 1, "orientation": "south-to-north", + "profile": [[0, 500], [50, 2000], [100, 800]], + "source": copy.deepcopy(SOURCE), + } + data.update(kw) + return data + + +def rec_with(data=None, hike_table=None): + rec = sample_record("X Trail") + rec["derived"]["elevation"] = data + rec["derived"]["has_line"] = data is not None + if data is not None: + rec["source"]["line_file"] = "line.geojson" + rec["derived"]["files"] = {"line": "x/line.geojson"} + if hike_table: + rec["hike"] = hike_table + return rec + + +def render(rec): + return trail.render(rec, GH)[2] + + +def text(fragment): + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))) + + +def glance_of(body): + return body[body.index('
    ", body.index('
    '):svg.index('')] + mi = svg[svg.index(''):] + self.assertIn("Distance along the track (km)", km) + self.assertIn("Elevation (m)", km) + self.assertIn("2,000", km) # a metre tick reaches the high point + self.assertIn("Distance along the track (mi)", mi) + self.assertIn("Elevation (ft)", mi) + self.assertNotIn("style=", svg) + # CSS shows one system, by the same data-units preference as lengths + with open(os.path.join(WEB, "assets", "style.css"), encoding="utf-8") as f: + css = f.read() + self.assertIn(".elev-profile .len__mi { display: none; }", css) + self.assertIn(':root[data-units="mi"] .elev-profile .len__mi { display: inline; }', css) + self.assertIn(':root[data-units="mi"] .elev-profile .len__km { display: none; }', css) + + def test_text_alternative_states_the_facts(self): + svg = str(elevation.profile_svg(elev())) + label = html.unescape(re.search(r'aria-label="([^"]*)"', svg).group(1)) + for want in ("3,000 m (9,843 ft)", "100.0 km (62 mi)", "500 m (1,640 ft)", + "2,000 m (6,562 ft)", "walking south to north"): + self.assertIn(want, label, want) + # the same sentence is the visible caption + self.assertIn(label, text(render(rec_with(elev())))) + + def test_no_elevation_file_shows_nothing(self): + body = render(rec_with(None)) + for absent in ("Elevation profile", "Low point", "Climb", 'id="elevation-data-title"', + 'id="elevation-title"', "detail--with-profile"): + self.assertNotIn(absent, body, absent) + self.assertIn("At a glance", body) # and the page is otherwise whole + + +class AboutTest(unittest.TestCase): + def test_method_credit_and_every_value(self): + data = elev(parts=2, part_starts_km=[50], profile=ProfileTest.PROFILE) + body = render(rec_with(data)) + about = body[body.index('
    Climb", row) + self.assertIn("3,000 m", text(row)) + self.assertIn("computed", text(row)) + row_none = home.entry(rec_with(None)) + self.assertIn('data-climb=""', row_none) + self.assertNotIn("
    Climb
    ", row_none) + self.assertIn('', 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) + + +class RoutesListTest(unittest.TestCase): + def _route(self): + rec = rec_with(None) + rec["derived"]["kind"] = "route" + rec["kind"] = "route" + rec["route"] = {"creator": "A Person", "year": 1970, "line_policy": "sold"} + rec["guide"] = [] + return rec + + def test_no_repetition_under_by_author_headings(self): + rec = self._route() + plain = home.entry(rec) + self.assertIn("Route by A Person, 1970", text(plain)) + self.assertIn('Route', plain) + _, _, body, _ = regions.routes_page([rec], GH) + self.assertIn("By A Person", text(body)) + self.assertNotIn("entry__by", body) + self.assertNotIn("tag--route", body) + + +class LoaderTest(unittest.TestCase): + def test_real_records(self): + pct = records.load_record(ROOT, "pacific-crest") + data = pct["derived"]["elevation"] + self.assertIsNotNone(data) + self.assertGreater(data["ascent_m"], 0) + self.assertIn("Terrain Tiles", data["source"]["attribution"]) + none_rec = records.load_record(ROOT, "sierra-high-route") + self.assertIsNone(none_rec["derived"]["elevation"]) + # elevation facts are derived, so they never appear as record fields + self.assertNotIn("ascent_m", text(trail.raw_record(pct))) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/tests/test_extra.py b/web/tests/test_extra.py index 737a2c2..f082d87 100644 --- a/web/tests/test_extra.py +++ b/web/tests/test_extra.py @@ -13,7 +13,7 @@ ROOT = os.path.dirname(WEB) sys.path.insert(0, WEB) import serve # noqa: E402 -from olt import docs, home, records, regions as regions_mod, seo, site, words # noqa: E402 +from olt import common, docs, facets, home, records, regions as regions_mod, seo, site, words # noqa: E402 OUT = os.path.join(WEB, ".cache", "test-site") @@ -83,7 +83,7 @@ class ExtraPagesTest(unittest.TestCase): def test_no_dead_internal_links_in_added_pages(self): import re - for rel in ("regions/index.html", "routes/index.html", "sources/index.html", + for rel in ("regions/index.html", "routes/index.html", "lists/index.html", "sources/index.html", "logos/index.html", "about/index.html", "data/index.html", "data/schema/index.html", "data/changelog/index.html"): html = read_out(rel) @@ -107,39 +107,31 @@ class ExtraPagesTest(unittest.TestCase): self.assertIn('href="/regions/us-vt/"', page) - def test_country_and_region_counts_match_the_regions_pages(self): + def test_where_counts_match_the_place_pages(self): home_doc = read_out("index.html") - index = read_out("regions/index.html") - by_slug, canada_wide = regions_mod.collect_regions(self.records) - for country, label in (("US", "United States"), ("CA", "Canada")): - shown = int(re.search(rf'value="{country}">{label} \((\d+)\)', home_doc).group(1)) - on_index = int(re.search(rf'data-country-count="{country}">(\d+)<', index).group(1)) - listed = set() - for slug, info in by_slug.items(): - if info["country"] == country: - listed |= set(entry_ids(read_out(f"regions/{slug}/index.html"))) - if country == "CA": - listed |= {r["id"] for r in canada_wide} - self.assertEqual(shown, on_index, country) - self.assertEqual(shown, len(listed), country) - # every row of those records says it touches the country - for tid in listed: - attrs = re.search(rf'
  • ]*)>', home_doc).group(1) - self.assertIn(country, re.search(r'data-countries="([^"]*)"', attrs).group(1).split(), tid) - self.assertIn('data-countries="US CA"', re.search( - r'
  • ]*>', home_doc).group(0)) - self.assertIn('data-countries="US CA"', re.search( - r'
  • ]*>', home_doc).group(0)) - # each region option's count is the number of records on that region's page - for value, n in re.findall(r'', home_doc): + by_slug, across = regions_mod.collect_regions(self.records) + # each state or province option's count is the number of trails on its place page + found = re.findall(r'', home_doc) + self.assertEqual({v for v, _ in found}, {i["key"] for i in by_slug.values()}) + for value, n in found: page = read_out(f"regions/{value.lower()}/index.html") self.assertEqual(int(n), len(entry_ids(page)), value) - canada = re.search(r'', home_doc) - self.assertEqual(int(canada.group(1)), len(canada_wide)) - self.assertIn('href="/?region=CA-*"', index) + # and the rows that say they are there + self.assertEqual(int(n), len(re.findall(rf'data-where="[^"]*\b{value}\b', home_doc)), value) + for country, label in (("US", "United States"), ("CA", "Canada")): + n = int(re.search(rf'', home_doc).group(1)) + self.assertEqual(n, sum(1 for r in self.records if country in common.countries(r)), country) + for g, name, _ in facets.PLACE_GROUPS: + m = re.search(rf'', home_doc) + n = sum(1 for r in self.records if g in facets.place_groups(r)) + self.assertEqual(int(m.group(1)) if m else 0, n, g) + self.assertTrue(across) + self.assertIn('id="across-canada"', read_out("regions/index.html")) + self.assertIn('id="canada-wide"', read_out("regions/index.html")) # the old anchor still lands def test_list_pages_share_the_home_list(self): - for rel in ("index.html", "regions/us-co/index.html", "routes/index.html"): + 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('
    '):] for part in ('