Rebuild the site for people browsing trails
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

The site read like a database. It is now a place to find and read about
long trails, and everything on it is still derived from the records.

- One kind of thing: a trail. A route is a kind of trail, explained
  where the word first appears. The navigation is Trails, Places, About.
- The home page is the catalogue, with filters for where, length, time,
  season, terrain, kind, walking, shape and GPX. A filter is offered
  only when at least a third of the trails have a value for it.
- Lists (for example National Scenic Trails and Routes) and a Places
  page that groups states and provinces into regions.
- A trail page leads with what a hiker needs: summary, at a glance,
  map, downloads, elevation profile and where to go next. The dataset's
  own fields sit in a collapsed "About this data" section.
- The trail list is a compact card on phones and beside the filters,
  and a column table where it has the full page width.
- web/serve.py takes --bind, for viewing from another device.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-14 01:32:22 -07:00
1 parent efb6164737
commit b817d2097b
21 files changed
+3468 -719

No files matched your search

+112 -63
View File
@@ -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 <details> (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);
+349 -18
View File
@@ -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; }
+111
View File
@@ -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/<key>/, 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}/"
+7 -31
View File
@@ -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'<abbr title="{esc(name)}">{esc(code)}</abbr>')
href = f"/regions/{words.region_key(code, rec['country']).lower()}/"
if linked:
text = Markup(f'<a href="{esc(href)}">{text}</a>')
parts.append(text)
return Markup(" ".join(parts))
def tags(rec, with_policy=True):
"""Kind, tier and listing tags, and (with_policy) the 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('<span class="tag tag--route">Person-defined route</span>')
elif rec.get("tier") == "national":
if route_tag and is_route(rec):
out.append('<a class="tag tag--route" href="/routes/">Route</a>')
if rec.get("tier") == "national":
out.append('<span class="tag tag--nst">National Scenic Trail</span>')
else:
out.append('<span class="tag">Designated trail</span>')
tier = rec.get("tier")
if tier in ("short", "deferred", "candidate"):
out.append(f'<span class="tag tag--quiet">{esc(words.label(words.TIERS, tier))}</span>')
if str(rec.get("wave")) == "held":
out.append('<span class="tag tag--quiet">Held</span>')
if is_route(rec) and with_policy:
out.append(policy_chip(policy(rec)))
return Markup("".join(out))
+136 -25
View File
@@ -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))} <code class="raw">{esc(k)}</code>')
head = ('<thead><tr><th scope="col">{0}</th><th scope="col">Records</th>'
'<th scope="col">With a track</th><th scope="col">Trails and routes</th></tr></thead>')
'<th scope="col">With a track</th><th scope="col">Trails</th></tr></thead>')
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'<a href="{esc(url)}">{esc(model)}</a>' if url else esc(model)) if model else "The elevation model"
items += (f'<p>{model_html}, used for {n} trail{"s" if n != 1 else ""}.</p>'
f'<p>{esc(attribution)}</p>')
elev_credit = (f'<div class="doc-block"><h3>Elevation model</h3>'
f'<p>The elevation figures and profiles on the trail pages were computed '
f'from each track and this model. Its credit, as it gives it:</p>{items}</div>')
computed = f"""<div class="container section">
<div class="section-head"><h2 id="sources-at-a-glance">At a glance</h2>
<p>Counted from the {len(records)} records. Each trail page names its own source, licence and credit.
@@ -191,10 +207,11 @@ def sources_page(records, site, repo_root):
<div class="doc-block"><h3>By track source</h3><div class="table-wrap"><table>
{head.format("Track source")}
<tbody>{group_rows(by_source, source_label)}</tbody></table></div></div>
{elev_credit}
</div>"""
doc_html = render_doc(read_doc(repo_root, "SOURCES.md"), site, drop_h1=True)
body = (f'<div class="page-head"><div class="container"><header class="titleblock">'
f'<div class="titleblock__text"><p class="kicker">Provenance</p><h1>Sources</h1>'
body = (f'<div class="page-head"><div class="container">{BREAD}<li aria-current="page">Sources</li></ol></nav><header class="titleblock">'
f'<div class="titleblock__text"><h1>Sources</h1>'
f'<p class="page-head__lede">Where the tracks come from, and the terms each source states.</p>'
f'</div></header></div></div>{computed}'
f'<div class="container section"><div class="prose doc">{doc_html}</div></div>')
@@ -224,8 +241,8 @@ def logos_page(records, site, repo_root):
<div><dt>Taken from</dt><dd>{src_html}</dd></div></dl></div>
</li>"""
counts = collections.Counter(r.get("shield", {}).get("status", "") for r in records)
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">Marks</p><h1>Logos</h1>
body = f"""<div class="page-head"><div class="container">{BREAD}<li aria-current="page">Logos</li></ol></nav><header class="titleblock">
<div class="titleblock__text"><h1>Logos</h1>
<p class="page-head__lede">Logos are shown only to identify each trail. They belong to their holders.</p>
</div></header></div></div>
<div class="container section"><div class="prose doc">{notice_html}{f'<p><a href="{esc(site.removal_url)}">Ask for a track or logo to be removed, or its credit changed</a>.</p>' if site.is_github else ""}</div></div>
@@ -238,27 +255,121 @@ logo not found (<code class="raw">logo-not-found</code>).</p></div>"""
return "Logos", "Trail logos, their holders, and how a holder can ask for removal.", Markup(body)
BREAD = Markup('<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/about/">About</a></li>')
ABOUT_PARTS = (
# (anchor or path, title, what it is)
("#what-this-is", "What this is", "A guide to the long trails, built from an open dataset"),
("#how-trails-are-chosen", "How trails are chosen", "The rule, and what held, deferred and candidate mean"),
("#when-a-gpx-is-included", "When a GPX is included", "Whose tracks may be passed on, and routes' authors' terms"),
("/data/", "Data and downloads", "Every trail and track in bulk, the per-trail files and the licences"),
("/sources/", "Sources and their terms", "Where each track comes from, and the terms each source states"),
("/logos/", "Logos", "Each trail's logo, who holds it, and how to ask for removal"),
("/data/schema/", "Record schema", "Every field of a trail's record (trail.toml) and what it means"),
("/data/changelog/", "Changelog", "What changed, release by release"),
("#correct-or-add", "Correct or add a trail", "Report a problem, suggest a trail, or edit the data"),
)
def _count_line(records, key, value):
return sum(1 for r in records if str(r.get(key, "")) == value)
def about_page(records, site, repo_root):
"""(title, description, body) for /about/."""
"""(title, description, body) for /about/: the hub for the project and the dataset."""
readme = read_doc(repo_root, "README.md")
main = link_requests(render_sections(readme, site,
["What this is, and what it is not", "Inclusion rule",
"How to use it", "Report an error", "Licences", "Sources"]), site)
found = sections_map(readme)
def quoted(title, heading):
body = found.get(title)
if body is None:
return ""
return link_requests(render_doc(f"### {heading}\n\n{body}", site), site)
what = quoted("What this is, and what it is not", "The dataset’s own words")
rule = quoted("Inclusion rule", "The rule as the dataset states it")
rest = link_requests(render_sections(readme, site, ["How to use it", "Licences", "Report an error"]), site)
contrib = render_doc(read_doc(repo_root, "CONTRIBUTING.md"), site, heading_offset=1)
extra = ""
cards = "".join(
f'<li><a href="{esc(href)}">{esc(title)}</a><small>{esc(what_)}</small></li>'
for href, title, what_ in ABOUT_PARTS)
n = len(records)
routes = sum(1 for r in records if common.is_route(r))
tiers = collections.Counter(r.get("tier", "") for r in records)
held = _count_line(records, "wave", "held")
tier_rows = "".join(
f'<tr><td>{esc(words.label(words.TIERS, t))} <code class="raw">{esc(t)}</code></td>'
f'<td>{esc(words.meaning(words.TIERS, t))}.</td><td class="num">{tiers[t]}</td></tr>'
for t in ("national", "regional", "short", "deferred", "candidate") if tiers[t])
policies = collections.Counter(common.policy(r) for r in records if common.is_route(r))
policy_rows = "".join(
f'<tr><td>{common.policy_chip(p)}</td><td>{esc(words.POLICIES[p][1])}. {esc(words.POLICIES[p][2])}</td>'
f'<td class="num">{policies[p]}</td></tr>'
for p in ("open", "sold", "withheld", "unclear") if policies[p])
lines = sum(1 for r in records if common.has_line(r))
forms = ""
if site.repo_url and site.is_github:
extra = (f'<p><a href="{esc(site.correction_url())}">Report a problem</a> with a record, or '
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a> that is missing: '
f'short forms, no git needed. Or fix or add a trail yourself in the source repository.</p>')
forms = (f'<ul class="linklist">'
f'<li><a href="{esc(site.correction_url())}">Report a problem</a><small>A short form, no git needed. '
f'Every trail page also has its own link, with the trail filled in.</small></li>'
f'<li><a href="{esc(site.new_trail_url)}">Suggest a trail</a><small>A short form for a trail that is missing</small></li>'
f'<li><a href="{esc(site.removal_url)}">Ask for a track or logo to be removed</a><small>For the holder of a track or a logo</small></li>'
f'<li><a href="{esc(site.repo_url)}">Edit the data yourself</a><small>The source repository: one text file per trail</small></li>'
f'</ul>')
elif site.issues_url:
extra = f'<p><a href="{esc(site.issues_url)}">Open an issue</a> to report an error.</p>'
if site.repo_url:
extra += f'<p>Source repository: <a href="{esc(site.repo_url)}">{esc(site.repo_url)}</a>.</p>'
forms = f'<p><a href="{esc(site.issues_url)}">Open an issue</a> to report an error.</p>'
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">The project</p><h1>About {esc(site.name)}</h1>
<p class="page-head__lede">{esc(site.tagline)}.</p></div></header></div></div>
<div class="container section"><div class="prose doc">{main}{extra}{contrib}</div></div>"""
return "About", f"What {site.name} is and is not, the inclusion rule, licences and how to contribute.", Markup(body)
<div class="titleblock__text"><h1>About {esc(site.name)}</h1>
<p class="page-head__lede">{esc(site.tagline)}. Everything about the project and the data behind it is here.</p></div></header>
<nav class="about-hub" aria-label="About this site"><ul class="linklist about-hub__list">{cards}</ul></nav>
</div></div>
<div class="container section"><div class="prose doc">
<section aria-labelledby="what-this-is"><h2 id="what-this-is">What this is</h2>
<p>{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 <a href="{esc(site.repo_url)}">public repository</a>, where anyone can propose a change.' if site.repo_url else ""}</p>
<p>The dataset calls each trail a <em>record</em>, and the pages under About use its terms. The rest of the
site calls them trails.</p>
{what}
</section>
<section aria-labelledby="how-trails-are-chosen"><h2 id="how-trails-are-chosen">How trails are chosen</h2>
<p>A trail is listed when it is a named, continuous walk, or a named loop, of at least 80&nbsp;km (50&nbsp;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&nbsp;km.</p>
<p>Each record has a <em>tier</em>, which says why it is listed. A record can also be <em>held</em>: listed,
but with something about it not yet settled, which its note says.</p>
<div class="table-wrap"><table><thead><tr><th scope="col">Tier</th><th scope="col">What it means</th><th scope="col">Records</th></tr></thead>
<tbody>{tier_rows}<tr><td>Held <code class="raw">wave = "held"</code></td><td>{esc(words.meaning(words.WAVES, "held"))}. Any tier can be held.</td><td class="num">{held}</td></tr></tbody></table></div>
<p>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 &ldquo;About this data&rdquo;.</p>
{rule}
</section>
<section aria-labelledby="when-a-gpx-is-included"><h2 id="when-a-gpx-is-included">When a GPX is included</h2>
<p>A track is included, as GPX and GeoJSON, only where its source&rsquo;s terms allow passing it on.
{lines} of the {n} trails have one. Where there is none, the trail&rsquo;s page says why and where to look.
Each track keeps its source&rsquo;s terms; the credit and licence are shown beside every map and download.</p>
<p>A route&rsquo;s track follows its author&rsquo;s choice. The dataset records that choice as the route&rsquo;s
<em>track policy</em>:</p>
<div class="table-wrap"><table><thead><tr><th scope="col">Track policy</th><th scope="col">What it means here</th><th scope="col">Routes</th></tr></thead>
<tbody>{policy_rows}</tbody></table></div>
<p>The author of a route who wants its record changed or removed can ask; see <a href="/logos/">Logos</a> for how,
or use the links below.</p>
</section>
<section aria-labelledby="correct-or-add"><h2 id="correct-or-add">Correct or add a trail</h2>
<p>Every trail page has a &ldquo;Report a problem&rdquo; link. Please say where a correction can be checked:
a source page, a map, or a measured track.</p>
{forms}
{rest}
{contrib}
</section>
</div></div>"""
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'<tr><td>{esc(a)}</td><td>{esc(b)}</td><td><a href="{esc(c)}">{esc(c)}</a></td></tr>'
for a, b, c in lic_rows)
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">Downloads</p><h1>Data</h1>
body = f"""<div class="page-head"><div class="container">{BREAD}<li aria-current="page">Data</li></ol></nav><header class="titleblock">
<div class="titleblock__text"><h1>Data and downloads</h1>
<p class="page-head__lede">Bulk files, the stable per-trail URLs, and the licences.</p></div></header></div></div>
<div class="container section">
<div class="section-head"><h2>Bulk downloads</h2><p>{len(records)} records. Sizes are this build's.</p></div>
@@ -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"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/data/">Data</a></li>
{BREAD}<li><a href="/data/">Data</a></li>
<li aria-current="page">Record schema</li></ol></nav>
<header class="titleblock"><div class="titleblock__text"><p class="kicker">Reference</p>
<h1>Record schema</h1></div></header></div></div>
@@ -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"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/data/">Data</a></li>
{BREAD}<li><a href="/data/">Data</a></li>
<li aria-current="page">Changelog</li></ol></nav>
<header class="titleblock"><div class="titleblock__text"><p class="kicker">Reference</p>
<h1>Changelog</h1></div></header></div></div>
+286
View File
@@ -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'<path class="elev-profile__line" d="{" ".join(paths)}"/>'
high_pt = max(profile, key=lambda p: p[1])
low_pt = min(profile, key=lambda p: p[1])
marks = "".join(
f'<circle class="elev-profile__mark" cx="{x(float(d)):.1f}" cy="{y(float(m)):.1f}" r="3.5"/>'
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'<line class="elev-profile__grid" x1="{LEFT}" y1="{yy:.1f}" '
f'x2="{LEFT + plot_w}" y2="{yy:.1f}"/>')
out.append(f'<text class="elev-profile__tick" x="{LEFT - 6}" y="{yy + 4:.1f}" '
f'text-anchor="end">{esc(_fmt_tick(label, ystep))}</text>')
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'<text class="elev-profile__tick" x="{xx:.1f}" y="{TOP + plot_h + 18}" '
f'text-anchor="{anchor}">{esc(_fmt_tick(label, xstep))}</text>')
middle_y = TOP + plot_h / 2
out.append(f'<text class="elev-profile__axis" x="14" y="{middle_y:.1f}" text-anchor="middle" '
f'transform="rotate(-90 14 {middle_y:.1f})">{esc(ytitle)}</text>')
out.append(f'<text class="elev-profile__axis" x="{LEFT + plot_w / 2:.1f}" y="{H - 4}" '
f'text-anchor="middle">{esc(xtitle)}</text>')
cls = "len__km" if system == "km" else "len__mi"
return f'<g class="{cls}">{"".join(out)}</g>'
axes = (f'<line class="elev-profile__frame" x1="{LEFT}" y1="{TOP + plot_h}" '
f'x2="{LEFT + plot_w}" y2="{TOP + plot_h}"/>'
f'<line class="elev-profile__frame" x1="{LEFT}" y1="{TOP}" '
f'x2="{LEFT}" y2="{TOP + plot_h}"/>')
return Markup(
f'<svg class="elev-profile" viewBox="0 0 {W} {H}" role="img" '
f'aria-label="{esc(summary_sentence(elev, loop))}" focusable="false">'
f"{axis_group('km')}{axis_group('mi')}{axes}{line}{marks}</svg>")
+310
View File
@@ -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."
+95
View File
@@ -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)]
+319 -217
View File
@@ -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'<abbr title="{esc(name)}">{esc(key.split("-", 1)[1])}</abbr>')
parts.append(f'<a href="{esc(facets.place_path(key))}">{text}</a>')
country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec))
return Markup(" ".join(parts) + f' <span aria-hidden="true">&middot;</span> {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'<p class="entry__partial">{esc(common.partial_short_text(rec))}</p>'
if common.line_differs(rec) else "")
return (f'<span class="line__status">{swatch}{esc(facets.GPX_SHORT[status])}</span>'
f'<span class="line__detail">GPX and GeoJSON</span>{partial}')
return f'<span class="line__status">{common.SWATCH_NONE}{esc(facets.GPX_SHORT[status])}</span>'
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 <author>" 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)} <span aria-hidden="true">&middot;</span> '
f'{esc(words.COUNTRIES.get(rec["country"], rec["country"]))}')
policy = common.policy_chip(common.policy(rec)) if route else ""
partial = common.line_differs(rec)
if common.has_line(rec):
partial_note = (f'<p class="entry__partial">{esc(common.partial_short_text(rec))}</p>'
if partial else "")
line = (f'<span class="line__status">{common.SWATCH_ROUTE if route else common.SWATCH_LINE}Track{policy}</span>'
f'{partial_note}'
f'<span class="line__detail">GeoJSON, GPX</span>'
f'<span class="line__detail">{esc(common.short_source(rec))} &middot; {esc(common.licence_label(rec))}</span>')
note = ""
else:
line = f'<span class="line__status">{common.SWATCH_NONE}Record only{policy}</span>'
note = (f'\n <p class="entry__note"><span class="vh">Why there is no track: </span>'
f'{esc(common.absent_reason_short(rec))}</p>')
regions = " ".join(words.region_key(c, rec["country"]) for c in rec.get("regions", []))
search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"]]
+ ([rec["route"]["creator"]] if route else [])).lower()
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"""<li class="entry"{data}>
tag_html = common.badges(rec, route_tag=not routes_list)
kicker = f'\n <p class="entry__kicker">{tag_html}</p>' if tag_html else ""
by = f'\n <p class="entry__by">{esc(facets.route_by(rec))}</p>' if route and not routes_list else ""
desc = entry_desc(rec)
desc_html = f'\n <p class="entry__desc">{esc(desc)}</p>' if desc else ""
time_html = esc(facets.time_text(rec)) + (' <small class="entry__est">estimate</small>' if est else "")
climb_html = (f'\n <div class="entry__climb"><dt>Climb</dt><dd>{words.elevation(elev["ascent_m"], "stack")}'
f'<small class="entry__est">computed</small></dd></div>') if elev else ""
return f"""<li class="entry"{attrs}>
{common.plate(rec)}
<div class="entry__body">
<p class="entry__kicker">{common.tags(rec, with_policy=False)}</p>
<{h} class="entry__name"><a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a> <span class="{abbr_cls}">{esc(rec.get("short_name", ""))}</span></{h}>
<p class="entry__desc">{esc(desc)}</p>
<p class="entry__where">{where}</p>
<div class="entry__body">{kicker}
<{h} class="entry__name"><a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a> <span class="{abbr_cls}">{esc(rec.get("short_name", ""))}</span></{h}>{by}{desc_html}
<p class="entry__where">{where_html(rec)}</p>
</div>
<dl class="entry__facts">
<div class="entry__length"><dt>Length</dt><dd>{words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}<span class="loglen" style="--km: {rec["length_km"]}" aria-hidden="true"></span></dd></div>
<div class="entry__line"><dt>Track</dt><dd class="line line--{"yes" if common.has_line(rec) else "no"}">{line}</dd></div>
</dl>{note}{extra}
<div class="entry__time"><dt>Time</dt><dd>{time_html}</dd></div>
<div class="entry__line"><dt>GPX</dt><dd class="line line--{"yes" if facets.gpx_here(rec) else "no"}">{gpx_cell(rec)}</dd></div>{climb_html}
</dl>{extra}
</li>"""
# The filters ------------------------------------------------------------------
def _length_options(steps, selected_any_last):
opts = [f'<option value="{km}">{km:,} km &middot; {words.fmt_int(words.km_to_mi(km))} mi</option>'
for km in steps]
@@ -121,97 +160,138 @@ def _length_options(steps, selected_any_last):
return '<option value="">Any</option>' + "".join(opts[:-1])
def region_options(c):
"""The region filter: each state, province and territory a record names, with the
count its /regions/ page shows; the Canada-wide records under their own option."""
groups = []
for country, table in (("US", words.US_STATES), ("CA", words.CA_PROVINCES)):
opts = []
if country == "CA" and c["region:CA-*"]:
key = words.region_key(words.ALL_CANADA, "CA")
opts.append(f'<option value="{esc(key)}">{esc(words.region_name(words.ALL_CANADA))} '
f'({c["region:" + key]})</option>')
for code, name in sorted(table.items(), key=lambda kv: kv[1]):
n = c[f"region:{country}-{code}"]
if n:
opts.append(f'<option value="{country}-{code}">{esc(name)} ({n})</option>')
groups.append(f'<optgroup label="{esc(words.COUNTRIES[country])}" data-country="{country}">{"".join(opts)}</optgroup>')
return "".join(groups)
def where_options(c):
"""The Where filter: the two countries, then each place group with its states and provinces."""
opts = [f'<option value="">Anywhere ({c["total"]})</option>']
for code in ("US", "CA"):
if c["where:" + code]:
opts.append(f'<option value="{code}">{esc(words.COUNTRIES[code])} ({c["where:" + code]})</option>')
for g, name, keys in facets.PLACE_GROUPS:
if not c["where:g:" + g]:
continue
inner = [f'<option value="g:{g}">All of {esc(name)} ({c["where:g:" + g]})</option>']
for key in sorted(keys, key=facets.place_name):
if c["where:" + key]:
inner.append(f'<option value="{key}">{esc(facets.place_name(key))} ({c["where:" + key]})</option>')
opts.append(f'<optgroup label="{esc(name)}">{"".join(inner)}</optgroup>')
if c["where:" + facets.ACROSS_CANADA]:
opts.append(f'<option value="{facets.ACROSS_CANADA}">{facets.ACROSS_CANADA_NAME} '
f'({c["where:" + facets.ACROSS_CANADA]})</option>')
return "".join(opts)
def finder_form(c, steps=LENGTH_STEPS):
tier_opts = "".join(
f'<option value="{t}">{esc(words.label(words.TIERS, t))} ({c["tier:" + t]})</option>'
for t in ("national", "regional", "short", "deferred", "candidate") if c["tier:" + t])
policy_opts = "".join(
f'<option value="{p}">{esc(words.label(words.POLICIES, p))}: {esc(words.meaning(words.POLICIES, p).lower())} ({c["policy:" + p]})</option>'
for p in ("open", "sold", "withheld", "unclear") if c["policy:" + p])
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'<span class="check__hint">{esc(hints[value])}</span>' if hints and hints.get(value) else ""
out.append(f'<label class="check"><input type="checkbox" name="{name}" value="{esc(value)}">'
f'<span class="check__text">{esc(label)} <span class="check__count">{n}</span></span>{hint}</label>')
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'<p class="field__hint filter-missing" data-missing="{key}" hidden>'
f'{esc(facets.missing_text(without, key))} They are left out while this filter is on.</p>')
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"""<div class="field">
<label class="field__label" for="where">{facets.WHERE}</label>
<select class="select" id="where" name="where">{where_options(c)}</select>
</div>""")
first.append(f"""<fieldset class="field">
<legend>{facets.LENGTH}</legend>
<div class="range">
<label class="vh" for="min">Shortest length</label>
<select class="select" id="min" name="min" data-length-options>{_length_options(steps, False)}</select>
<span class="range__to" aria-hidden="true">to</span>
<label class="vh" for="max">Longest length</label>
<select class="select" id="max" name="max" data-length-options>{_length_options(steps, True)}</select>
</div>
<p class="field__hint" id="len-hint" aria-live="polite">Any length.</p>
</fieldset>""")
first.append(f"""<fieldset class="field">
<legend>{facets.TIME}</legend>
<div class="pills">{_checks("time", [(k, label) for k, label, _ in facets.TIME_BANDS], c, "time")}</div>
<p class="field__hint">To walk it all. Where no source says, it is estimated from the length.</p>
</fieldset>""")
if facets.offered(records, "season"):
month_opts = "".join(f'<option value="{i}">{esc(m)} ({c[f"month:{i}"]})</option>'
for i, m in enumerate(facets.MONTHS, 1))
first.append(f"""<div class="field">
<label class="field__label" for="month">{facets.SEASON}</label>
<select class="select" id="month" name="month"><option value="">Any month</option>{month_opts}</select>
<p class="field__hint">Trails usually walked in that month.</p>
{_missing(records, "season")}
</div>""")
if facets.offered(records, "terrain"):
first.append(f"""<fieldset class="field">
<legend>{facets.TERRAIN}</legend>
<div class="pills">{_checks("terrain", facets.TERRAIN_VALUES.items(), c, "terrain")}</div>
{_missing(records, "terrain")}
</fieldset>""")
first.append(f"""<fieldset class="field">
<legend>{facets.KIND}</legend>
<div class="seg">
<label><input type="radio" name="kind" value="" checked><span>Any</span></label>
<label><input type="radio" name="kind" value="trail"><span>Official trails ({c["kind:trail"]})</span></label>
<label><input type="radio" name="kind" value="route"><span>Routes ({c["kind:route"]})</span></label>
</div>
<p class="field__hint"><a href="/routes/">What is a route?</a></p>
</fieldset>""")
if facets.offered(records, "walking"):
more.append(f"""<fieldset class="field">
<legend>{facets.WALKING}</legend>
{_checks("walking", facets.WALKING_VALUES.items(), c, "walking", facets.WALKING_HINT)}
{_missing(records, "walking")}
</fieldset>""")
if facets.offered(records, "shape"):
more.append(f"""<fieldset class="field">
<legend>{facets.SHAPE}</legend>
{_checks("shape", facets.SHAPES.items(), c, "shape")}
{_missing(records, "shape")}
</fieldset>""")
more.append(f"""<fieldset class="field">
<legend>{facets.GPX}</legend>
{_checks("gpx", facets.GPX_STATUS.items(), c, "gpx")}
</fieldset>""")
return f"""<form class="filters" id="finder-form" role="search" aria-label="Find a trail">
<div class="filters__search field">
<label class="field__label" for="q">Search</label>
<input class="input" id="q" name="q" type="search" placeholder="Name, abbreviation or creator" autocomplete="off" spellcheck="false">
<input class="input" id="q" name="q" type="search" placeholder="Name, abbreviation or author of a route" autocomplete="off" spellcheck="false">
</div>
<div class="field">
<label class="check">
<input type="checkbox" name="line">
<span class="check__text">Has a downloadable track <span class="check__count">{c["line"]}</span></span>
<span class="check__hint">GeoJSON and GPX. The other {c["record_only"]} are records only.</span>
</label>
</div>
<details class="filters__more">
<summary>Filters <span class="filters__active"></span></summary>
<div class="filters__form">
<fieldset class="field">
<legend>Country</legend>
<div class="seg">
<label><input type="radio" name="country" value="all" checked><span>Both ({c["total"]})</span></label>
<label><input type="radio" name="country" value="US"><span>United States ({c["country:US"]})</span></label>
<label><input type="radio" name="country" value="CA"><span>Canada ({c["country:CA"]})</span></label>
</div>
<p class="field__hint">A record that crosses the border counts under both.</p>
</fieldset>
<div class="field">
<label class="field__label" for="region">State, province or territory</label>
<select class="select" id="region" name="region"><option value="">Any</option>{region_options(c)}</select>
</div>
<fieldset class="field field--wide">
<legend>Length</legend>
<div class="range">
<label class="vh" for="min">Shortest length</label>
<select class="select" id="min" name="min" data-length-options>{_length_options(steps, False)}</select>
<span class="range__to" aria-hidden="true">to</span>
<label class="vh" for="max">Longest length</label>
<select class="select" id="max" name="max" data-length-options>{_length_options(steps, True)}</select>
</div>
<p class="field__hint" id="len-hint" aria-live="polite">Any length.</p>
</fieldset>
<fieldset class="field">
<legend>Kind</legend>
<label class="check">
<input type="checkbox" name="designated" checked>
<span class="check__text">Designated trails <span class="check__count">{c["designated"]}</span></span>
<span class="check__hint">Designated by a land agency or a trail association</span>
</label>
<label class="check">
<input type="checkbox" name="route" checked>
<span class="check__text">Person-defined routes <span class="check__count">{c["route"]}</span></span>
<span class="check__hint">Worked out and published by a person or a small group</span>
</label>
<label class="field__label field__label--sub" for="policy">Route track policy</label>
<select class="select" id="policy" name="policy"><option value="">Any</option>{policy_opts}</select>
</fieldset>
<div class="field">
<label class="field__label" for="tier">Tier</label>
<select class="select" id="tier" name="tier"><option value="">Any</option>{tier_opts}</select>
</div>
<div class="field field--wide">
<button class="button button--quiet" type="reset">Clear search and filters</button>
</div>
<details class="filters__panel" open>
<summary>Filters <span class="filters__count"></span></summary>
<div class="filters__first">
{"".join(first)}
</div>
</details>
<details class="filters__more">
<summary>More filters <span class="filters__active"></span></summary>
<div class="filters__form">
{"".join(more)}
</div>
</details>
<div class="field filters__reset">
<button class="button button--quiet" type="reset">Clear search and filters</button>
</div>
</form>"""
# The list ---------------------------------------------------------------------
# The length strip's ticks (style.css .loglen): 100, 1,000 and 10,000 km.
SCALE_KM = (100, 1000, 10000)
@@ -227,8 +307,10 @@ def list_head():
f'<span class="len__mi">{words.fmt_int(words.km_to_mi(km))}{mi_unit}</span></span>')
return f"""<div class="list-head" aria-hidden="true">
<span>Trail</span>
<span>Length<span class="list-head__scale">{"".join(ticks)}</span></span>
<span>Track</span>
<span>{facets.LENGTH}<span class="list-head__scale">{"".join(ticks)}</span></span>
<span>{facets.TIME}</span>
<span>{facets.GPX}</span>
<span>Climb</span>
</div>"""
@@ -245,35 +327,40 @@ SORT_SELECT = """<label class="results-sort">Sort
<option value="name">Name, A to Z</option>
<option value="long">Longest first</option>
<option value="short">Shortest first</option>
<option value="quick">Quickest first</option>
<option value="climb">Most climb first</option>
</select>
</label>"""
def key():
def key(official=True):
"""official: False on a list of routes only, which has no official trail to explain."""
first = f"<li>{common.SWATCH_LINE}Official trail with a GPX here</li>\n " if official else ""
return f"""<ul class="key" aria-label="Key to the list">
<li>{common.SWATCH_LINE}Track in the dataset</li>
<li>{common.SWATCH_NONE}Record only; the note says why</li>
<li>Route track policy:
{common.policy_chip("open")} {common.policy_chip("sold")} {common.policy_chip("withheld")} {common.policy_chip("unclear")}
</li>
{first}<li>{common.SWATCH_ROUTE}Route with a GPX here</li>
<li>{common.SWATCH_NONE}No GPX here: its page says where to get one</li>
</ul>"""
def results(recs=None, *, finder=False, groups=None):
"""The list of records, as every page shows it: div.results > head, key, list head, ol.entries.
def results(recs=None, *, finder=False, groups=None, routes_list=False):
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
finder: the home page's list, driven by the finder form (live count, sort, empty state).
groups: [(heading, records, extra_fn)] to list the records under level-3 headings
(the routes page); extra_fn(rec) gives HTML placed last in each row.
finder: the home page's list, driven by the filters (live count, sort, empty state).
groups: [(heading, trails, extra_fn)] to list the trails under level-3 headings;
extra_fn(rec) gives HTML placed last in each row.
routes_list: passed to entry() for the Routes list (see there).
"""
if groups is None:
groups = [(None, recs, None)]
total = sum(len(g[1]) for g in groups)
noun = "record" if total == 1 else "records"
shown = [r for g in groups for r in g[1]]
only_routes = bool(shown) and all(facets.kind(r) == "route" for r in shown)
noun = ("route" if only_routes else "trail") + ("" if total == 1 else "s")
lists = ""
for heading, items, extra_fn in groups:
level = 4 if heading else 3
rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "") for r in items)
rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "",
routes_list=routes_list) for r in items)
if heading:
lists += f'\n <h3 class="results__group">{heading}</h3>'
list_id = ' id="entries"' if finder else ""
@@ -284,7 +371,7 @@ def results(recs=None, *, finder=False, groups=None):
tools = SORT_SELECT + "\n " + UNITS_TOGGLE
empty = """
<div class="empty-state" id="empty-state" hidden>
<p><strong>No records match these filters.</strong></p>
<p><strong>No trails match these filters.</strong></p>
<button class="button button--quiet" type="button" data-reset>Clear search and filters</button>
</div>"""
else:
@@ -298,80 +385,95 @@ def results(recs=None, *, finder=False, groups=None):
{tools}
</div>
</div>
{key()}
{key(official=not only_routes)}
{list_head()}{lists}{empty}
</div>""")
# 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('<p class="note">None of these trails has a GPX here, so there is no track to draw. '
'Each trail&rsquo;s page says where to get one.</p>')
if len(ids) < MAP_MIN and scope != "all":
names = words.join_names(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>'
for r in recs if r["id"] in ids)
return Markup(f'<p class="note">Only {names} {"has" if len(ids) == 1 else "have"} a GPX here, '
'so no map of them all is drawn. Each trail&rsquo;s page says where to get a track.</p>')
ids_attr = "" if scope == "all" else f' data-ids="{esc(" ".join(ids))}"'
n = len(ids)
return Markup(f"""<figure class="mapfig{" mapfig--wide" if wide else ""}" data-map="overview" data-src="/data/overview.geojson"{ids_attr}{overview_bbox(recs)}>
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
<div class="map" role="region" aria-label="{esc(label)}">
<div class="map__fallback"></div>
<div class="map__canvas"></div>
<p class="map__status" role="status">The map needs JavaScript. The list has every trail.</p>
</div>
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
</div>
<figcaption class="mapfig__caption">
<ul class="legend" aria-label="Legend">
<li>{common.SWATCH_LINE}Official trail</li>
<li>{common.SWATCH_ROUTE}Route</li>
</ul>
<p>{n} track{"s" if n != 1 else ""}, simplified for display. Select one for its name. Each trail&rsquo;s page names its source, credit and licence. Base map: OpenFreeMap, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;OpenStreetMap contributors.</p>
</figcaption>
</figure>""")
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'<li><a href="{esc(browse.path(lst))}">{esc(lst.title)} <span class="chips__n">{len(recs)}</span></a></li>'
for lst, recs in browse.shown(records) if not lst.key.startswith("terrain-"))
if not items:
return ""
return f"""<nav class="lists-row" aria-labelledby="lists-title">
<h2 id="lists-title" class="lists-row__title">Start from a list</h2>
<ul class="chips">{items}<li><a href="/lists/">All lists</a></li></ul>
</nav>"""
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&nbsp;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'<p class="hero__caveat">Something wrong, or a trail missing? '
contribute = (f'<p class="finder__foot">Something wrong, or a trail missing? '
f'<a href="{esc(site.correction_url())}">Report a problem</a> or '
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a>; '
f'the records are text files <a href="{esc(site.repo_url)}">anyone can fix or add to</a>.</p>')
return f"""<section class="hero" aria-labelledby="hero-title">
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a>.</p>')
return f"""<section class="hero hero--short" aria-labelledby="hero-title">
<div class="container hero__inner">
<p class="kicker">A public dataset &middot; United States and Canada</p>
<h1 id="hero-title">{esc(site.tagline)}</h1>
<h1 id="hero-title">Find a long trail</h1>
<p class="hero__lede">{lede}</p>
<p class="hero__caveat">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.</p>
{contribute}
<p><a class="button button--primary hero__cta" href="#q">Find a trail</a></p>
<div class="hero__counts">
<dl class="tally">
<div><dt>Records</dt><dd>{total}</dd></div>
<div><dt><a href="/?kind=designated">Designated trails</a></dt><dd>{c["designated"]}</dd></div>
<div><dt><a href="/?kind=route">Person-defined routes</a></dt><dd>{c["route"]}</dd></div>
<div><dt>{common.SWATCH_LINE}<a href="/?line=1">With a track</a></dt><dd>{c["line"]}</dd></div>
<div><dt>{common.SWATCH_NONE}Records only</dt><dd>{c["record_only"]}</dd></div>
</dl>
<div class="ratio" aria-hidden="true"><span class="ratio__line" style="--n: {c["line"]}"></span><span class="ratio__none" style="--n: {c["record_only"]}"></span></div>
</div>
{lists_row(records)}
</div>
</section>
<section class="section" aria-labelledby="map-title">
<div class="container">
<div class="section-head">
<h2 id="map-title">Every track in the dataset</h2>
<p>{c["line"]} tracks, simplified for display. Select a trail on the map for its name.</p>
</div>
<figure class="mapfig" data-map="overview" data-src="/data/overview.geojson"{overview_bbox(records)}>
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
<div class="map" role="region" aria-label="Map of every track in the dataset">
<div class="map__fallback"></div>
<div class="map__canvas"></div>
<p class="map__status" role="status">The map needs JavaScript. The list below has every record.</p>
</div>
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
</div>
<figcaption class="mapfig__caption">
<ul class="legend" aria-label="Legend">
<li>{common.SWATCH_LINE}Designated trail</li>
<li>{common.SWATCH_ROUTE}Person-defined route</li>
</ul>
<p>Tracks are simplified to about 750&nbsp;m here; each keeps the credit and licence named on its page. Base map: OpenFreeMap, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;OpenStreetMap contributors.</p>
</figcaption>
</figure>
</div>
</section>
<section class="section" id="finder" aria-labelledby="finder-title">
<section class="section section--finder" id="finder" aria-labelledby="finder-title">
<div class="container finder__grid">
<div class="finder__head section-head">
<h2 id="finder-title">Find a trail</h2>
<p>Search, then narrow by country, region, length, kind and track</p>
<h2 class="vh" id="finder-title">Every trail</h2>
{finder_form(records, c, length_steps(records))}
<div class="finder__main">
{overview_map(records, "Map of the trails the filters leave", wide=True, scope="all")}
{results(recs, finder=True)}
</div>
<div class="finder__notes">
<p class="finder__foot">Not for navigation: tracks vary in quality and some trails are unfinished. Check each trail&rsquo;s own maps before you go.</p>
{contribute}
</div>
{finder_form(c, length_steps(records))}
{results(recs, finder=True)}
</div>
</section>"""
+29 -24
View File
@@ -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'<div class="container prose">...{esc(some_text)}...</div>'
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'<li><a href="{esc(site.correction_url())}">Report an error in a record</a></li>'
report = (f'<li><a href="{esc(site.correction_url())}">Report a problem</a></li>'
f'<li><a href="{esc(site.new_trail_url)}">Suggest a trail</a></li>'
f'<li><a href="{esc(site.repo_url)}">Fix or add a trail</a></li>')
return Markup(f"""<footer class="site-footer">
<div class="container site-footer__grid">
<div class="site-footer__about">
<a class="wordmark" href="/"><span class="wordmark__blaze" aria-hidden="true"></span>{esc(site.name)}</a>
<p>A dataset, not a navigation product: tracks vary in quality, some trails are unfinished, and some records have no track at all. Check a trail&rsquo;s own record before using its track.</p>
<p>The records are public domain (CC0-1.0). Each track keeps the terms of its source, named on its page. Tracks from OpenStreetMap are &copy;&nbsp;OpenStreetMap contributors, under the ODbL. Logos belong to their holders and are shown only to identify each trail.</p>
<p>Not for navigation: tracks vary in quality, some trails are unfinished, and some have no GPX here. Check a trail&rsquo;s own maps before you go.</p>
<p>The trail data is public domain (CC0-1.0). Each track keeps the terms of its source, named on its page. Tracks from OpenStreetMap are &copy;&nbsp;OpenStreetMap contributors, under the ODbL. Logos belong to their holders and are shown only to identify each trail.</p>
</div>
<nav aria-labelledby="footer-data">
<h2 id="footer-data">Data</h2>
<nav aria-labelledby="footer-browse">
<h2 id="footer-browse">Trails</h2>
<ul>
<li><a href="/data/">About the data and downloads</a></li>
<li><a href="/data/trails.csv">trails.csv</a>: one row per trail</li>
<li><a href="/data/index.geojson">index.geojson</a>: every track, simplified</li>
<li><a href="/sources/">Sources and their terms</a></li>
<li><a href="/">Every trail</a></li>
<li><a href="/regions/">Places</a></li>
<li><a href="/lists/">Lists</a></li>
<li><a href="/routes/">Routes</a></li>
</ul>
</nav>
<nav aria-labelledby="footer-project">
<h2 id="footer-project">Project</h2>
<h2 id="footer-project">About</h2>
<ul>
<li><a href="/about/">About {esc(site.name)}</a></li>
<li><a href="/logos/">Logos and removal requests</a></li>
<li><a href="/data/">Data and downloads</a></li>
<li><a href="/sources/">Sources and their terms</a></li>
<li><a href="/logos/">Logos</a></li>
{report}
</ul>
</nav>
@@ -99,10 +104,10 @@ def footer(site):
</div>
</fieldset>
<fieldset class="field">
<legend>Lengths</legend>
<legend>Units</legend>
<div class="seg">
<label><input type="radio" name="units" value="km" checked><span>km first</span></label>
<label><input type="radio" name="units" value="mi"><span>miles first</span></label>
<label><input type="radio" name="units" value="km" checked><span>km and m first</span></label>
<label><input type="radio" name="units" value="mi"><span>mi and ft first</span></label>
</div>
</fieldset>
</div>
+24 -10
View File
@@ -8,6 +8,9 @@ writes:
/trails/<id>/index.html one page per record
/trails/<id>/trail.toml the raw record; release.txt beside it where the trail has one
/trails/<id>/shield-thumb.png the list-size copy of a PNG logo (olt/thumbs.py)
/regions/, /regions/<slug>/ Places: the hub and one page per state or province
/lists/, /lists/<key>/ 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 += """<div class="container section">
<form class="notfound-search" action="/" method="get" role="search">
<label class="field__label" for="notfound-q">Search the trails and routes</label>
<input class="input" id="notfound-q" name="q" type="search" placeholder="Name, abbreviation or creator" autocomplete="off" spellcheck="false">
<label class="field__label" for="notfound-q">Search the trails</label>
<input class="input" id="notfound-q" name="q" type="search" placeholder="Name, abbreviation or author of a route" autocomplete="off" spellcheck="false">
<button class="button button--primary" type="submit">Search</button>
</form>
<p class="prose"><a href="/">Find a trail</a> on the home page, or browse <a href="/regions/">by region</a>.</p>
<p class="prose"><a href="/">Find a trail</a> on the home page, or browse by <a href="/regions/">place</a>.</p>
</div>"""
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
+3
View File
@@ -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
+166 -161
View File
@@ -1,180 +1,137 @@
"""Region pages (/regions/, /regions/<slug>/) and the routes page (/routes/).
"""Places (/regions/, /regions/<state or province>/), lists (/lists/, /lists/<key>/) 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 ('<p class="note">No downloadable track in this region yet, so there is '
'nothing to draw. The records below say why.</p>')
return f"""<figure class="mapfig" data-map="overview" data-src="/data/overview.geojson" data-ids="{esc(" ".join(ids))}"{_bbox_attr(recs)}>
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
<div class="map" role="region" aria-label="Map of tracks in {esc(title)}">
<div class="map__fallback"></div><div class="map__canvas"></div>
<p class="map__status" role="status">The map needs JavaScript. The list below has every record.</p>
</div>
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
</div>
<figcaption class="mapfig__caption">
<ul class="legend" aria-label="Legend"><li>{common.SWATCH_LINE}Designated trail</li>
<li>{common.SWATCH_ROUTE}Person-defined route</li></ul>
<p>{len(ids)} track{"s" if len(ids) != 1 else ""} in this region, simplified for display. Select a trail on the map for its name.</p>
</figcaption>
</figure>"""
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 = '<div><dt>Records</dt><dd>' + str(len(records)) + '</dd></div>'
for country in ("US", "CA"):
n_country = len(country_records(records, country))
tally += (f'<div><dt><a href="#{esc(country.lower())}">{esc(words.COUNTRIES[country])}</a></dt>'
f'<dd data-country-count="{esc(country)}">{n_country}</dd></div>')
infos = sorted((i for i in by_slug.values() if i["country"] == country),
key=lambda i: i["name"].lower())
rows = ""
for info in infos:
lines = sum(1 for r in info["records"] if common.has_line(r))
rows += (f'<tr><td><a href="{esc(region_path(info["code"], country))}">{esc(info["name"])}</a> '
f'<code class="raw">{esc(info["code"])}</code></td>'
f'<td class="num">{len(info["records"])}</td><td class="num">{lines}</td></tr>')
extra = ""
if country == "CA" and canada_wide:
links = ", ".join(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>' for r in canada_wide)
extra = (f'<div class="doc-block" id="{CANADA_WIDE_ID}"><h3>All provinces and territories</h3>'
f'<p class="prose">These records name <em>all provinces and territories</em> rather than '
f'one province, so they have no single region page and are not counted under each '
f'province: {links}. <a href="/?region={esc(CANADA_WIDE_KEY)}">Open in the trail finder</a>.</p></div>')
unit = "state" if country == "US" else "province or territory, or all of them"
blocks += f"""<div class="doc-block"><h2 id="{esc(country.lower())}">{esc(words.COUNTRIES[country])}</h2>
<p class="prose">{n_country} records name at least one {unit}. Each is counted once, whichever
country it is filed under.</p>
<div class="table-wrap"><table><thead><tr><th scope="col">State, province or territory</th><th scope="col">Records</th><th scope="col">With a downloadable track</th></tr></thead>
<tbody>{rows}</tbody></table></div>{extra}</div>"""
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'<li><a href="#{esc(g)}">{esc(name)} <span class="chips__n">{len(recs)}</span></a></li>')
rows = "".join(
f'<li><a href="{esc(facets.place_path(i["key"]))}">{esc(i["name"])}</a>'
f'<span class="places__n">{_plural(len(i["records"]))}</span></li>'
for i in infos)
blocks += f"""<section class="places__group" aria-labelledby="{esc(g)}">
<h2 id="{esc(g)}">{esc(name)}</h2>
<p class="places__sum">{_plural(len(recs))}, {_gpx_count(recs)} with a GPX here.
<a href="/?where=g:{esc(g)}">See them with the filters</a></p>
<ul class="places__list">{rows}</ul>
</section>"""
if across:
links = ", ".join(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>' for r in across)
jump.append(f'<li><a href="#across-canada">{facets.ACROSS_CANADA_NAME} <span class="chips__n">{len(across)}</span></a></li>')
blocks += f"""<section class="places__group" aria-labelledby="across-canada">
<h2 id="across-canada"><span id="canada-wide"></span>{facets.ACROSS_CANADA_NAME}</h2>
<p class="places__sum">{_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&rsquo;s page.</p>
</section>"""
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"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">Browse</p><h1>Regions</h1>
<p class="page-head__lede">Every state, province and territory a record names. A record that
crosses several regions appears on each region's page, under the country that region belongs to.</p>
<div class="titleblock__text"><h1>Places</h1>
<p class="page-head__lede">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&rsquo;s page.</p>
</div></header>
<dl class="tally">{tally}</dl></div></div>
<div class="container section">{blocks}</div>"""
return "Regions", "Long trails by state, province and territory, with counts of records and tracks.", Markup(body)
<ul class="chips" aria-label="Jump to a part of the country">{"".join(jump)}</ul></div></div>
<div class="container section places">{blocks}</div>"""
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/<slug>/: 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'<a href="{esc(region_path(p["code"], p["country"]))}">← {esc(p["name"])}</a>')
if idx + 1 < len(same):
n = by_slug[same[idx + 1]]
neighbours.append(f'<a href="{esc(region_path(n["code"], n["country"]))}">{esc(n["name"])} →</a>')
nav = " · ".join(neighbours)
with_line = (f'<a href="/?region={esc(key)}&amp;line=1">With a track</a>' 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 = '<li><a href="/regions/">Places</a></li>'
if group:
crumbs += f'<li><a href="/regions/#{esc(group)}">{esc(group_name)}</a></li>'
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'<a href="{esc(facets.place_path(k))}">{esc(facets.place_name(k))}</a>')
nav = (f'<nav class="region-nav" aria-label="Elsewhere in {esc(group_name)}">Elsewhere in {esc(group_name)}: '
f'{" · ".join(siblings)}</nav>') if siblings else ""
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/regions/">Regions</a></li>
<li><a href="/regions/#{esc(info["country"].lower())}">{esc(words.COUNTRIES[info["country"]])}</a></li>
<li aria-current="page">{esc(info["name"])}</li></ol></nav>
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{crumbs}<li aria-current="page">{esc(info["name"])}</li></ol></nav>
<header class="titleblock"><div class="titleblock__text">
<p class="kicker">{esc(words.COUNTRIES[info["country"]])} · {esc(info["code"])}</p>
<p class="kicker">{esc(group_name + " · " if group_name else "")}{esc(country)}</p>
<h1>{esc(info["name"])}</h1>
<p class="page-head__lede">{len(recs)} record{"s" if len(recs) != 1 else ""}, {lines} with a downloadable track.</p>
<p class="page-head__lede">{_plural(len(recs))} in {esc(info["name"])}, {n_gpx} with a GPX here.
<a href="/?where={esc(key)}">Narrow them with the filters</a>.</p>
</div></header>
<dl class="tally"><div><dt>Records</dt><dd>{len(recs)}</dd></div>
<div><dt>{common.SWATCH_LINE}{with_line}</dt><dd>{lines}</dd></div>
<div><dt>{common.SWATCH_NONE}Records only</dt><dd>{len(recs) - lines}</dd></div></dl>
</div></div>
<div class="container section">
<div class="section-head"><h2>Tracks in {esc(info["name"])}</h2><p>Only tracks in this region are drawn.</p></div>
{_region_map(recs, info["name"])}
</div>
<div class="container section">
<div class="section-head"><h2>Trails and routes in {esc(info["name"])}</h2>
<p><a href="/?region={esc(key)}">Open these in the trail finder</a> to search and filter them.</p></div>
<div class="container section place">
{home.overview_map(recs, f"Map of the trails in {info['name']}")}
{home.results(recs)}
<nav class="region-nav" aria-label="Neighbouring regions"><a href="/regions/">All regions</a>{f' · {nav}' if nav else ""}</nav>
{nav}
</div>"""
title = info["name"]
return title, f"{len(recs)} long trails and routes in {info['name']}, {words.COUNTRIES[info['country']]}.", Markup(body), bool(lines)
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'<li><a href="{esc(g.get("url", ""))}">{esc(g.get("title", ""))}</a>'
f' <span class="access access--{esc(access)}">{esc(words.ACCESS.get(access, access))}</span>'
@@ -185,36 +142,84 @@ def route_guides(rec):
f'<ul class="route-guides">{items}</ul></div>')
def routes_page(records, site, repo_root):
"""(title, description, body) for /routes/."""
readme = docs.sections_map(docs.read_doc(repo_root, "README.md"))
inc = readme.get("Inclusion rule", "")
paras = [p for p in inc.split("\n\n") if "Person-defined rout" in p and "at the same 50-mile floor" in p]
bullets = [p for p in inc.split("\n\n") if "The creator sells" in p]
explainer = "\n\n".join(paras + bullets) or readme.get("Person-defined routes", "")
intro = docs.render_doc("## What a person-defined route is\n\n" + explainer, site)
policy_items = ""
for key in ("open", "sold", "withheld", "unclear"):
lab, short, rule = words.POLICIES[key]
policy_items += f'<li>{common.policy_chip(key)}<span>{esc(short)}. {esc(rule)}</span></li>'
policies = Markup(f'<ol class="policy-scale" aria-label="The four track policies">{policy_items}</ol>')
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"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">Person-defined routes</p><h1>Routes</h1>
<p class="page-head__lede">{len(routes)} routes worked out and published by a person or a small group.</p>
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"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/">Trails</a></li>
<li><a href="/lists/">Lists</a></li><li aria-current="page">Routes</li></ol></nav>
<header class="titleblock"><div class="titleblock__text"><p class="kicker">A list</p><h1>Routes</h1>
<p class="page-head__lede" id="what-is-a-route">{esc(facets.ROUTE_DEFINITION)}</p>
</div></header></div></div>
<div class="container section"><div class="prose doc">{intro}</div>
<h2 class="doc-block">The four track policies</h2>{policies}
<p class="prose"><a href="/?kind=route">See the routes in the trail finder</a>, or read a route below.</p></div>
<div class="container section"><div class="section-head"><h2>Routes by creator</h2>
<p>Each route links to its record; its guides link out to the creator's or publisher's page.</p></div>
{home.results(groups=groups)}</div>"""
return "Routes", f"{len(routes)} person-defined routes by creator, with track policies and guides.", Markup(body)
<div class="container section">
<div class="prose">
<p>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&rsquo;s page says what the walking is.</p>
<p>{_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&rsquo;s page says whether its author gives the track away, sells it, or does not publish it.
<a href="/?kind=route">Narrow them with the filters</a>.</p>
</div>
</div>
<div class="container section">
{home.overview_map(routes, "Map of the routes with a GPX here")}
{home.results(groups=groups, routes_list=True)}
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
</div>"""
return "Routes", f"{_plural(len(routes), 'route')} in the United States and Canada, by author, with their guides.", Markup(body), n_gpx >= home.MAP_MIN
def list_page(lst, recs, total, site):
"""(title, description, body, needs_map) for /lists/<key>/."""
n_gpx = _gpx_count(recs)
rule = (f"Lists are picked out by rule from each trail&rsquo;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"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/">Trails</a></li>
<li><a href="/lists/">Lists</a></li><li aria-current="page">{esc(lst.title)}</li></ol></nav>
<header class="titleblock"><div class="titleblock__text">
<p class="kicker">A list</p>
<h1>{esc(lst.title)}</h1>
<p class="page-head__lede">{esc(lst.blurb)} {_plural(len(recs))}, {n_gpx} with a GPX here.</p>
</div></header>
</div></div>
<div class="container section">
{home.overview_map(recs, f"Map of the trails in the list {lst.title}")}
{home.results(recs)}
<p class="finder__foot">{rule}</p>
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
</div>"""
return lst.title, f"{lst.title}: {lst.blurb}", Markup(body), n_gpx >= home.MAP_MIN
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'<li><a href="{esc(common.trail_path(r))}">{common.name(r)}</a> '
f'<span class="shelf__len">{words.length(r["length_km"], "short", r["derived"]["length_mi"])}</span></li>'
for r in recs[:4])
cards.append(f"""<li class="shelf">
<h2 class="shelf__title"><a href="{esc(browse.path(lst))}">{esc(lst.title)}</a> <span class="shelf__count">{len(recs)}</span></h2>
<p class="shelf__blurb">{esc(lst.blurb)}</p>
<ul class="shelf__items">{sample}</ul>
<p class="shelf__more"><a href="{esc(browse.path(lst))}">See all {len(recs)}<span class="vh">: {esc(lst.title)}</span></a></p>
</li>""")
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/">Trails</a></li><li aria-current="page">Lists</li></ol></nav>
<header class="titleblock"><div class="titleblock__text"><h1>Lists</h1>
<p class="page-head__lede">Ready-made selections of the {len(records)} trails, a way to start. Each is
picked out by rule from what each trail&rsquo;s page says, so a list grows as trails are added.</p>
</div></header></div></div>
<div class="container section"><ul class="shelves">{"".join(cards)}</ul>
<p class="finder__foot">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 <a href="/">the home page</a>.</p></div>"""
return "Lists", "Ready-made lists of long trails: National Scenic Trails, routes, loops, the longest and more.", Markup(body)
+459 -110
View File
@@ -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'<a href="{esc(href)}">{esc(words.region_name(code_))}</a>')
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'<abbr title="{esc(name)}">{esc(key.split("-", 1)[1])}</abbr>')
parts.append(f'<a href="{esc(facets.place_path(key))}">{text}</a>')
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'<details class="define"><summary>What is a route?</summary>'
f'<p>{esc(facets.ROUTE_DEFINITION)} <a href="/routes/">Every route</a>.</p></details>')
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'<li><a href="/">Trails</a></li>',
f'<li><a href="/?country={esc(rec["country"])}">{esc(country)}</a></li>']
if route:
crumbs.append('<li><a href="/?kind=route">Person-defined routes</a></li>')
crumbs = ['<li><a href="/regions/">Places</a></li>']
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'<li><a href="/regions/#{esc(g)}">{esc(facets.GROUP_NAME[g])}</a></li>')
crumbs.append(f'<li><a href="{esc(facets.place_path(keys[0]))}">{esc(facets.place_name(keys[0]))}</a></li>')
elif groups:
crumbs.append(f'<li><a href="/regions/#across-canada">{esc(facets.ACROSS_CANADA_NAME)}</a></li>')
crumbs.append(f'<li aria-current="page">{common.name(rec)}</li>')
if route:
r = rec["route"]
lead = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "")
else:
lead = rec.get("designation", "")
sub = f'{esc(lead)} &middot; {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'<a class="button button--link" href="{esc(official[0])}">{esc(official[1])} {common.ICON_EXTERNAL}</a>')
if rec["derived"].get("downloads"):
actions.append(f'<a class="button button--primary" href="#download">{common.ICON_DOWNLOAD}Download the GPX</a>')
else:
actions.append(f'<a class="button button--quiet" href="#track">GPX: {esc(facets.GPX_STATUS[facets.gpx(rec)])}</a>')
tag_html = common.badges(rec)
kicker = f'<p class="cluster">{tag_html}</p>' if tag_html else ""
lead = lead_line(rec)
define = route_definition() if route else ""
return f"""<div class="page-head">
<div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{"".join(crumbs)}</ol></nav>
<header class="titleblock{" titleblock--with-plate" if has_plate else ""}">
{plate}
<div class="titleblock__text">
<p class="cluster">{common.tags(rec)}</p>
{kicker}
<h1>{common.name(rec)} <span class="titleblock__abbr">{esc(rec.get("short_name", ""))}</span></h1>
<p class="titleblock__sub">{sub}</p>
{f'<p class="titleblock__sub">{common.rich(lead)}</p>' if lead else ""}
{define}
</div>
</header>
{tally(rec)}
<p class="trail-lede">{lede}</p>
<p class="cluster trail-actions">{"".join(actions)}</p>
</div>
</div>"""
def tally(rec):
v = rec.get("verification", {})
note = rec.get("length_note", "")
if note.replace(",", "") in (f"{rec['length_km']} km", f"{rec['length_km']} km published"):
note = "" # the note only repeats the number
items = [("Published length", words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]), note)]
if v.get("verified") and "measured_km" in v:
diff = v.get("difference_percent", 0)
items.append(("Measured 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"<small>{note if isinstance(note, Markup) else esc(note)}</small>" if note else ""
value_html = value if isinstance(value, Markup) else esc(value)
return Markup(f'<div{" class=\"glance__wide\"" if wide else ""}><dt>{esc(label)}</dt>'
f'<dd>{value_html}{note_html}</dd></div>')
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}{"<br>" 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}<br>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])}<span class="glance__to"> to </span>{esc(text[1])}')
if facets.shape(rec):
text = Markup(f'<strong>{esc(facets.SHAPES[facets.shape(rec)])}.</strong> {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'<a href="#download">{esc(text)}</a>') 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('<span class="tally__none">Not measured</span>'),
"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'<a href="#download">{esc(text)}</a>') 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'<div><dt>{esc(a)}</dt><dd>{esc(b)}{f"<small>{esc(c)}</small>" if c else ""}</dd></div>'
for a, b, c in items)
return Markup(f'<dl class="tally tally--trail">{cells}</dl>')
value = Markup(f'<a href="#track">{esc(facets.GPX_STATUS[status])}</a>')
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("<div>", '<div class="glance__wide">', 1))
caution = ""
if h.get("caution"):
caution = f'<p class="glance__warn"><strong>Know before you go.</strong> {common.rich(common.sentence(h["caution"]))}</p>'
unfinished = ""
if h.get("unfinished"):
unfinished = f'<p class="glance__warn"><strong>Not finished.</strong> {common.rich(common.sentence(h["unfinished"]))}</p>'
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'<p class="note">{esc(names)} {verb} not on file for this trail yet.</p>'
elev_caveat = elevation.coverage_caveat(elev) if elev else ""
elev_note = f'<p class="note">{esc(elev_caveat)}</p>' if elev_caveat else ""
return f"""<section class="glance detail__glance" aria-labelledby="glance-title">
<h2 class="glance__title" id="glance-title">At a glance</h2>
<dl class="glance__facts">{"".join(rows)}</dl>
{unfinished}{caution}{elev_note}{pending}
</section>"""
# Map or empty frame ---------------------------------------------------------
@@ -187,25 +316,65 @@ def map_figure(rec):
</figure>"""
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'<p class="note">{esc(caveat)}</p>' if caveat else ""
if not elevation.show_profile(elev):
return f"""<section class="elev detail__profile" aria-labelledby="elevation-title">
<h2 class="elev__title" id="elevation-title">Elevation profile</h2>
<div class="elev__body">
<p>{esc(elevation.parts_caveat(elev))}</p>
<p>{esc(sentence)}</p>
{caveat_html}
</div>
</section>"""
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"""<section class="elev detail__profile" aria-labelledby="elevation-title">
<h2 class="elev__title" id="elevation-title">Elevation profile</h2>
<figure class="elev__figure">
{elevation.profile_svg(elev, loop)}
<figcaption><p>{esc(sentence)}{esc(breaks)}</p>{caveat_html}</figcaption>
</figure>
</section>"""
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'<a class="button button--primary" href="{esc(g["url"])}">'
f'{esc(g["title"])} {common.ICON_EXTERNAL}</a>')
@@ -214,31 +383,42 @@ def empty_frame(rec):
elif len(rec.get("guide", [])) > 1:
actions.append('<a class="button button--link" href="#guides-title">All guides</a>')
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'<a class="button button--link" href="{esc(src["publisher_url"])}">'
f'Publisher&rsquo;s page {common.ICON_EXTERNAL}</a>')
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'<a class="button button--link" href="{esc(official[0])}">'
f'{esc(official[1])} {common.ICON_EXTERNAL}</a>')
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'<a class="button button--link" href="{esc(src["url"])}">'
f'The source {common.ICON_EXTERNAL}</a>')
f'{esc(label)} {common.ICON_EXTERNAL}</a>')
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)}</p><p class="note"><strong>Why there is none here:</strong> '
f'{common.rich(reason)}')
actions_html = f'<p class="cluster">{"".join(actions)}</p>' if actions else ""
return f"""<figure class="mapfig mapfig--empty detail__map" aria-labelledby="noline-title">
return f"""<figure class="mapfig mapfig--empty detail__map" id="track" aria-labelledby="noline-title">
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true">No track in this dataset</span>
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true">No GPX here</span>
<div class="map map--empty">
<div class="map__message">
<p class="kicker">Record only</p>
<p class="kicker">GPX: {esc(facets.GPX_STATUS[status])}</p>
<h2 id="noline-title">{esc(title)}</h2>
<p>{common.rich(reason)}</p>
<p class="map__reason">{reason if isinstance(reason, Markup) else common.rich(reason)}</p>
<p class="note">{esc(rule)}</p>
{actions_html}
</div>
</div>
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true">Nothing drawn</span>
</div>
<figcaption class="mapfig__caption"><p>No map is drawn: the dataset holds no track for this {"route" if common.is_route(rec) else "trail"}, and does not guess one.</p></figcaption>
<figcaption class="mapfig__caption"><p>No map is drawn: there is no track for this trail here, and the site does not guess one.</p></figcaption>
</figure>"""
@@ -368,7 +548,7 @@ def guides_panel(rec):
<h2 class="panel__head" id="guides-title">Where to get the route</h2>
<div class="panel__body">
<ul class="guides">{cards}</ul>
<p class="note">Links go to the creator&rsquo;s or publisher&rsquo;s own page for each guide.</p>
<p class="note">Links go to the author&rsquo;s or publisher&rsquo;s own page for each guide.</p>
</div>
</section>"""
@@ -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'<li>{ext_link(u, t)}<small>{esc(describe(u, w))}</small></li>' for u, (t, w) in items.items())
return f"""<section class="panel" aria-labelledby="links-title">
<h2 class="panel__head" id="links-title">Links</h2>
<div class="panel__body"><ul class="linklist">{lis}</ul></div>
</section>"""
return block("links-title", "Links", Markup(f'<ul class="linklist">{lis}</ul>'))
# Main column ----------------------------------------------------------------
@@ -439,14 +616,14 @@ def policy_scale(current):
here = ' aria-current="true"' if p == current else ""
mark = '<span class="policy-scale__here">This route</span>' if p == current else ""
items.append(f'<li{here}>{common.policy_chip(p)}<span>{esc(short)}. {esc(rule)}</span>{mark}</li>')
return Markup(f'<ol class="policy-scale" aria-label="Track policies for person-defined routes">{"".join(items)}</ol>')
return Markup(f'<ol class="policy-scale" aria-label="Track policies for routes">{"".join(items)}</ol>')
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 = ('<span class="tag tag--quiet">Not the creator&rsquo;s words</span>'
if r.get("creator_words_by") else '<span class="tag tag--quiet">The creator&rsquo;s words</span>')
not_creator = ('<span class="tag tag--quiet">Not the author&rsquo;s words</span>'
if r.get("creator_words_by") else '<span class="tag tag--quiet">The author&rsquo;s words</span>')
url = r.get("creator_words_url", "")
quote = f"""<figure class="quote">
<blockquote{f' cite="{esc(url)}"' if url else ""}><p>{esc(r["creator_words"])}</p></blockquote>
@@ -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' <span class="muted">({esc(names)})</span>' if names else ""
where = Markup(f'{common.regions_html(rec, linked=True)}{names_html}, {esc(country)}')
codes = Markup(" ".join(f'<a href="{esc(facets.place_path(k))}">{esc(k.split("-", 1)[1] if k != facets.ACROSS_CANADA else facets.ACROSS_CANADA_NAME)}</a>'
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'<div><dt>Model page</dt><dd>{ext_link(src["url"])}</dd></div>') 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&rsquo;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'<h3 class="block__sub">Limits</h3>{record_text(limits)}') if limits else ""
content = Markup(f'<p class="record-text">{method}</p>') + 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"""<div class="notice">
<h3>If you made this route</h3>
<p>A route&rsquo;s creator can ask for its record to be corrected or removed, and the record will be corrected or removed. Say which route: {code(rec["id"])}. See <a href="/about/">About</a>.</p>
<p>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 <a href="/about/">About</a>.</p>
</div>""")
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"<li>{link}{f'<small>{esc(detail)}</small>' if detail else ''}</li>"
body = f'<ul class="linklist">{items}</ul>' if items else \
'<p class="record-text">The record names no page for these facts.</p>'
checked = f'<p class="note">Checked {esc(h["checked"])}.</p>' 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"""<details class="about-data" id="about-data">
<summary><h2 id="about-data-title">About this data</h2>
<span class="about-data__hint">Where the track and the facts come from, licence, checks, the logo, corrections, and every field of the record</span></summary>
<div class="about-data__body detail__main">
{blocks}
</div>
</details>"""
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'<a href="{esc(site.correction_url(rec["id"], rec.get("name", "")))}">Report a problem</a>.')
return (f'<p class="page-foot">Not for navigation: check the trail&rsquo;s own maps '
f'and current conditions before you go.{report}</p>')
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'<li><a href="{esc(common.trail_path(r))}">{common.name(r)}</a>'
f'<span class="onward__len">{words.length(r["length_km"], "short", r["derived"]["length_mi"])}'
f'{" · Route" if common.is_route(r) else ""}</span></li>'
for r in recs[:ONWARD_MAX])
more = (f'<p class="onward__more"><a href="{esc(more_href)}">{esc(more_text)}</a></p>'
if more_href else "")
return (f'<section class="onward__part" aria-labelledby="{heading_id}">'
f'<h3 id="{heading_id}">{esc(title)}</h3><ul class="onward__list">{items}</ul>{more}</section>')
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'<nav class="onward" aria-labelledby="onward-title"><h2 id="onward-title">Where next</h2>'
f'<div class="onward__grid">{"".join(parts)}</div></nav>')
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'<aside class="detail__aside" aria-label="{"Downloads" if has_map else "Where to get the route"}">'
f'{aside}</aside>') if aside else ""
profile = elevation_figure(rec)
body = f"""{page_head(rec)}
<div class="container detail">
<div class="container detail{"" if aside else " detail--no-aside"}{"" if has_map else " detail--no-map"}{" detail--with-profile" if profile else ""}">
{glance(rec)}
{map_figure(rec) if has_map else empty_frame(rec)}
<aside class="detail__aside" aria-label="{"Downloads and links" if has_map else "Where to get it, and links"}">
{aside}
</aside>
<div class="detail__main">
{main}
</div>
{profile}
{aside_html}
</div>
<div class="container trail-more">
{onward(rec, records)}
{page_foot(rec, site)}
{about_data(rec, site)}
</div>"""
return rec["name"], description(rec), body, has_map
+72 -9
View File
@@ -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'<span class="len len--{style}"><span class="len__km">{esc(km_text)}</span>'
f'<span class="len__mi">{esc(mi_text)}</span></span>')
# 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'<span class="len len--{style}"><span class="len__km">{esc(fmt_int(m))} m</span>'
f'<span class="len__mi">{esc(fmt_int(ft))} ft</span></span>')
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]
+5 -3
View File
@@ -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()
+284
View File
@@ -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('<section class="glance'):body.index("</section>", body.index('<section class="glance'))]
def top_part(body):
return body[:body.index('<details class="about-data"')]
class GlanceTest(unittest.TestCase):
def test_computed_rows_without_a_sourced_high_point(self):
t = text(glance_of(render(rec_with(elev()))))
self.assertIn("High point 2,000 m 6,562 ft Computed from the track.", t)
self.assertIn("Low point 500 m 1,640 ft Computed from the track.", t)
# descent within a few percent of the climb is not shown
self.assertIn("Climb 3,000 m 9,843 ft Computed from the track, walking south to north.", t)
self.assertNotIn("Descent", t)
def test_descent_shown_when_it_differs(self):
t = text(glance_of(render(rec_with(elev(descent_m=1000)))))
self.assertIn("Descent: 1,000 m 3,281 ft", t)
self.assertIn("walking south to north", t)
self.assertFalse(elevation.show_descent(elev(ascent_m=1000, descent_m=951)))
self.assertTrue(elevation.show_descent(elev(ascent_m=1000, descent_m=949)))
def test_sourced_high_point_is_kept(self):
rec = rec_with(elev(), {"high_point": "Example Peak", "high_point_m": 2025, "checked": "2026-11-13"})
t = text(glance_of(render(rec)))
self.assertIn("High point Example Peak 2,025 m 6,644 ft", t)
self.assertNotIn("2,000 m", t) # the computed highest does not replace it
# the computed low point and climb still appear, marked as computed
self.assertIn("Low point 500 m", t)
self.assertIn("Climb 3,000 m", t)
def test_sourced_name_without_an_elevation_stays_as_it_was(self):
rec = rec_with(elev(), {"high_point": "Example Peak", "checked": "2026-11-13"})
t = text(glance_of(render(rec)))
self.assertIn("High point Example Peak", t)
self.assertNotIn("2,000 m", t)
def test_sea_level_low_point(self):
data = elev(lowest={"m": 0, "lat": 43.0, "lon": -124.0})
t = text(glance_of(render(rec_with(data))))
self.assertIn("Low point 0 m 0 ft Sea level. Computed from the track.", t)
self.assertIn("low point of sea level", elevation.summary_sentence(data))
def test_loop_climb_has_no_direction(self):
rec = rec_with(elev(), {"shape": "loop", "checked": "2026-11-13"})
t = text(glance_of(render(rec)))
self.assertIn("Climb 3,000 m 9,843 ft Computed from the track.", t)
self.assertNotIn("walking south to north", text(top_part(render(rec))))
class CaveatTest(unittest.TestCase):
def test_partial_coverage(self):
for cov, shown in ((0.84, True), (0.85, False), (1.0, False)):
data = elev(coverage=cov, track_km=cov * 100)
t = text(top_part(render(rec_with(data))))
if shown:
self.assertIn("for the track only", t)
self.assertIn(f"about {round(cov * 100)}% of the published length", t)
else:
self.assertNotIn("for the track only", t, cov)
self.assertEqual(elevation.coverage_percent(elev(coverage=0.002)), "less than 1%")
def test_over_coverage(self):
for cov, shown in ((1.16, True), (1.15, False)):
data = elev(coverage=cov, track_km=cov * 100)
t = text(top_part(render(rec_with(data))))
if shown:
self.assertIn("the climb is overstated", t)
self.assertIn("side trails or alternates", t)
else:
self.assertNotIn("overstated", t, cov)
def test_many_parts_draw_no_profile(self):
for parts, drawn in ((elevation.PROFILE_MAX_PARTS, True), (elevation.PROFILE_MAX_PARTS + 1, False)):
body = render(rec_with(elev(parts=parts)))
self.assertEqual("elev-profile__line" in body, drawn, parts)
if not drawn:
self.assertIn("No profile is drawn", text(body))
self.assertIn(f"{parts} in the elevation sampling", text(body))
# the figures are still there
self.assertIn("Climb 3,000 m", text(glance_of(body)))
class ProfileTest(unittest.TestCase):
# two parts: the point at 50 km ends the first, the next at 50 km starts the second
PROFILE = [[0, 500], [25, 900], [50, 700], [50, 1200], [75, 2000], [100, 800]]
def test_breaks_at_part_boundaries(self):
segs = elevation.segments(self.PROFILE, [50])
self.assertEqual([[p[0] for p in s] for s in segs], [[0, 25, 50], [50, 75, 100]])
data = elev(parts=2, part_starts_km=[50], profile=self.PROFILE)
svg = str(elevation.profile_svg(data))
path = re.search(r'<path class="elev-profile__line" d="([^"]*)"', svg).group(1)
self.assertEqual(path.count("M"), 2) # one subpath per part, never joined
self.assertIn("The line breaks where the track does", text(render(rec_with(data))))
def test_repeated_part_starts_each_break(self):
profile = [[0, 1], [10, 2], [10, 3], [10, 4], [20, 5]]
self.assertEqual(len(elevation.segments(profile, [10, 10])), 3)
def test_axes_in_both_units(self):
svg = str(elevation.profile_svg(elev()))
km = svg[svg.index('<g class="len__km">'):svg.index('<g class="len__mi">')]
mi = svg[svg.index('<g class="len__mi">'):]
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('<details class="about-data"'):]
t = text(about)
self.assertIn('id="elevation-data-title"', about)
for want in ("computed from the trail’s track and Example Model",
"A point was taken every 30 m along each part of the track",
"Example Model credit, as it gives it.",
"Highest point on the track 2,000 m", "At 40.00000, -105.00000",
"Lowest point on the track 500 m", "Total climb 3,000 m",
"Total descent 2,900 m", "Length sampled 100.0 km",
"Coverage 1.000", "Parts 2", "Part starts 50.0 km",
"Computed 2026-11-13",
"Computed from a public elevation model, not measured on the ground."):
self.assertIn(want, t, want)
self.assertIn('href="https://model.example/"', about)
def test_model_credit_on_the_sources_page(self):
_, _, body = docs.sources_page([rec_with(elev()), rec_with(None)], GH, ROOT)
self.assertIn("Elevation model", body)
self.assertIn("Example Model credit, as it gives it.", body)
self.assertIn('href="https://model.example/"', body)
class CatalogueTest(unittest.TestCase):
def test_climb_in_the_row_and_the_sort(self):
row = home.entry(rec_with(elev()))
self.assertIn('data-climb="3000"', row)
self.assertIn("<dt>Climb</dt>", 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("<dt>Climb</dt>", row_none)
self.assertIn('<option value="climb">Most climb first</option>', home.SORT_SELECT)
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
js = f.read()
self.assertIn("key === 'climb'", js)
# a trail with no computed climb sorts last, not first
self.assertIn("a.dataset.climb === '' ? -1", js)
self.assertIn("return bc - ac", js)
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('<a class="tag tag--route" href="/routes/">Route</a>', 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()
+48 -39
View File
@@ -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}"><span>{label} \((\d+)\)</span>', home_doc).group(1))
on_index = int(re.search(rf'data-country-count="{country}">(\d+)<', index).group(1))
listed = set()
for slug, info in by_slug.items():
if info["country"] == country:
listed |= set(entry_ids(read_out(f"regions/{slug}/index.html")))
if country == "CA":
listed |= {r["id"] for r in canada_wide}
self.assertEqual(shown, on_index, country)
self.assertEqual(shown, len(listed), country)
# every row of those records says it touches the country
for tid in listed:
attrs = re.search(rf'<li class="entry" data-id="{tid}"([^>]*)>', home_doc).group(1)
self.assertIn(country, re.search(r'data-countries="([^"]*)"', attrs).group(1).split(), tid)
self.assertIn('data-countries="US CA"', re.search(
r'<li class="entry" data-id="eastern-continental-trail"[^>]*>', home_doc).group(0))
self.assertIn('data-countries="US CA"', re.search(
r'<li class="entry" data-id="great-plains-trail"[^>]*>', home_doc).group(0))
# each region option's count is the number of records on that region's page
for value, n in re.findall(r'<option value="((?:US|CA)-[A-Z]{2})">[^<(]+\((\d+)\)</option>', home_doc):
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'<option value="((?:US|CA)-[A-Z]{2})">[^<(]+\((\d+)\)</option>', 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'<option value="CA-\*">All provinces and territories \((\d+)\)</option>', home_doc)
self.assertEqual(int(canada.group(1)), len(canada_wide))
self.assertIn('href="/?region=CA-*"', index)
# 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'<option value="{country}">{label} \((\d+)\)</option>', 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'<option value="g:{g}">All of {re.escape(name)} \((\d+)\)</option>', 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('<div class="results">'):]
for part in ('<div class="list-head" aria-hidden="true">', '<ol class="entries"',
@@ -148,9 +140,9 @@ class ExtraPagesTest(unittest.TestCase):
scale = re.search(r'<div class="list-head".*?</div>', results, re.S).group(0)
self.assertEqual(scale.count('class="len__km"'), 3, rel)
self.assertEqual(scale.count('class="len__mi"'), 3, rel)
for name in ("Length", "Time", "GPX"):
self.assertIn(f"<span>{name}", scale, rel)
self.assertNotIn('class="route-item"', read_out("routes/index.html"))
co = read_out("regions/us-co/index.html")
self.assertIn('<a href="/?region=US-CO&amp;line=1">With a track</a>', co)
def test_routes_page_rows_carry_their_guides(self):
doc = read_out("routes/index.html")
@@ -160,18 +152,35 @@ class ExtraPagesTest(unittest.TestCase):
row = re.search(rf'<li class="entry" data-id="{r["id"]}".*?\n</li>', doc, re.S).group(0)
for g in r["guide"]:
self.assertIn(f'href="{html.escape(g["url"], quote=True)}"', row, r["id"])
# says what a route is, in the one definition, and no longer explains track policies
self.assertIn(html.escape(facets.ROUTE_DEFINITION, quote=True), doc)
self.assertNotIn("track policies", doc.lower())
self.assertNotIn("policy-scale", doc)
def test_home_finder_layout(self):
doc = read_out("index.html")
form = doc[doc.index('<form class="filters"'):doc.index("</form>")]
self.assertIn('<details class="filters__more">', form)
self.assertNotIn("filters__more\" open", form)
# the line checkbox comes straight after the search field, outside the details
self.assertLess(form.index('name="line"'), form.index("<details"))
self.assertLess(form.index('id="q"'), form.index('name="line"'))
self.assertIn('<a class="button button--primary hero__cta" href="#q">Find a trail</a>', doc)
self.assertIn("No records match these filters.", doc)
steps = [int(v) for v in re.findall(r'<option value="(\d+)">', form[form.index('id="max"'):])]
self.assertIn("No trails match these filters.", doc)
more = form[form.index('<details class="filters__more">'):]
first = form[:form.index('<details class="filters__more">')]
# the first-rank filters in view, Walking, Shape and GPX behind "More"
for name in ("q", "where", "min", "max", "time", "kind"):
self.assertIn(f'name="{name}"', first, name)
for name in ("gpx",):
self.assertIn(f'name="{name}"', more, name)
for name, key in (("month", "season"), ("terrain", "terrain")):
self.assertEqual(f'name="{name}"' in first, facets.offered(self.records, key), name)
for name, key in (("walking", "walking"), ("shape", "shape")):
self.assertEqual(f'name="{name}"' in more, facets.offered(self.records, key), name)
# no dataset filters
for name in ("tier", "policy", "designated", "line", "country", "region"):
self.assertNotIn(f'name="{name}"', form, name)
# the map is in the tool, beside the list it filters
main = doc[doc.index('<div class="finder__main">'):]
self.assertLess(main.index('data-map="overview"'), main.index('<ol class="entries" id="entries">'))
steps = [int(v) for v in re.findall(r'<option value="(\d+)">', form[form.index('id="max"'):form.index("</select>", form.index('id="max"'))])]
self.assertGreaterEqual(steps[-1], max(r["length_km"] for r in self.records))
self.assertEqual(home.length_steps(self.records)[:11], list(home.LENGTH_STEPS))
@@ -193,7 +202,7 @@ class ExtraPagesTest(unittest.TestCase):
# a record's "none (no line included)" is shown in words, not as the raw value
self.assertIn("<td>None (no track included)</td>", page)
self.assertNotIn("none (no line included)", page)
self.assertEqual(page.count('<th scope="col">Trails and routes</th>'), 2)
self.assertEqual(page.count('<th scope="col">Trails</th>'), 2)
self.assertNotRegex(page, r'<td><a href="/trails/[^"]+/">[^<]*</a>, <a')
def test_data_page_licences_from_the_records(self):
+318
View File
@@ -0,0 +1,318 @@
"""Tests for the site's taxonomy and vocabulary (olt/facets.py and the pages that use it):
each attribute's name and values, the time estimate, the place grouping, filtering
with missing values and the coverage threshold, one word for one thing on every
browsing page, and the URLs the live site has always had.
The fixture tests need no built site; BuiltVocabularyTest builds it (as test_pages does).
"""
import html
import os
import re
import subprocess
import sys
import unittest
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from olt import facets, home, records, trail, words # noqa: E402
from test_hike import GH, fake, text, top_part # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
def route(i=1, policy="sold", **kw):
rec = fake(i, **kw)
rec["kind"] = "route"
rec["derived"]["kind"] = "route"
rec["route"] = {"creator": "Andrew Skurka", "year": 2018, "line_policy": policy}
rec["guide"] = [{"title": "Guide", "author": "Andrew Skurka", "access": "purchase",
"url": "https://guide.example/", "format": "book"}]
return rec
class AttributeTest(unittest.TestCase):
def test_names(self):
self.assertEqual((facets.WHERE, facets.LENGTH, facets.TIME, facets.SEASON, facets.TERRAIN,
facets.KIND, facets.WALKING, facets.SHAPE, facets.GPX),
("Where", "Length", "Time", "Season", "Terrain", "Kind", "Walking", "Shape", "GPX"))
def test_values(self):
self.assertEqual(list(facets.TERRAIN_VALUES), ["alpine", "forest", "desert", "coast", "prairie",
"canyon", "tundra", "lakes", "farmland"])
self.assertEqual(facets.WALKING_VALUES, {"trail": "On trail", "trail-and-road": "Trail and road",
"some-cross-country": "Some cross-country",
"mostly-cross-country": "Mostly cross-country"})
self.assertEqual(facets.SHAPES, {"point-to-point": "End to end", "loop": "Loop", "network": "Network"})
self.assertEqual(facets.KINDS, {"trail": "Official trail", "route": "Route"})
self.assertEqual([label for _, label, _ in facets.TIME_BANDS],
["A week or less", "One to two weeks", "Two to four weeks", "One to three months",
"More than three months"])
self.assertEqual(facets.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 test_kind_and_route_line(self):
self.assertEqual(facets.kind(fake(1)), "trail")
self.assertEqual(facets.route_by(fake(1)), "")
r = route()
self.assertEqual(facets.kind(r), "route")
self.assertEqual(facets.route_by(r), "Route by Andrew Skurka, 2018")
del r["route"]["year"]
self.assertEqual(facets.route_by(r), "Route by Andrew Skurka")
def test_walking_is_not_kind(self):
# a route on maintained trail says so; an official trail can have road walks
r = route(hike={"travel": "trail"})
self.assertEqual(facets.walking(r), "trail")
t = fake(2, hike={"travel": "trail-and-road"})
self.assertEqual(facets.kind(t), "trail")
self.assertEqual(facets.walking(t), "trail-and-road")
page = text(top_part(trail.render(r, GH)[2]))
self.assertIn("Walking On trail", page)
self.assertIn("Route by Andrew Skurka, 2018", page)
self.assertIn("What is a route?", page)
self.assertIn(facets.ROUTE_DEFINITION, page)
def test_gpx_status(self):
cases = [(fake(1), "elsewhere"), (route(policy="open"), "free"), (route(policy="sold"), "sold"),
(route(policy="withheld"), "unpublished"), (route(policy="unclear"), "elsewhere")]
for rec, want in cases:
self.assertEqual(facets.gpx(rec), want, rec.get("route"))
from test_hike import with_line
partial = with_line(fake(1))
self.assertEqual(facets.gpx(partial), "partial")
whole = with_line(fake(1))
whole["verification"]["difference_percent"] = -2.0
self.assertEqual(facets.gpx(whole), "here")
self.assertEqual(set(facets.GPX_STATUS.values()),
{"GPX to download here", "Partial GPX to download here", "Free from its author",
"Sold by its author", "Not published", "Not here, see the official site"})
def test_designation_badge_only_for_nst(self):
self.assertIn("National Scenic Trail", home.entry(fake(1, tier="national")))
for tier in ("regional", "short", "deferred", "candidate"):
self.assertNotIn("tag--", home.entry(fake(1, tier=tier)), tier)
class TimeTest(unittest.TestCase):
def test_stated(self):
rec = fake(1, hike={"days": [150, 210]})
self.assertEqual(facets.time_days(rec), (150, 210, False))
self.assertEqual(facets.time_text(rec), "5 to 7 months")
self.assertEqual(facets.estimate_note(rec), "")
self.assertEqual(facets.time_band(rec), "long")
def test_estimate_from_length(self):
rec = fake(1, km=300) # 300 km at 20 to 30 km a day: 10 to 15 days
self.assertEqual(facets.time_days(rec), (10, 15, True))
self.assertEqual(facets.time_text(rec), "About 1 to 2 weeks")
self.assertEqual(facets.estimate_note(rec), "Estimated from the length, at 20 to 30 km (12 to 19 mi) a day.")
self.assertEqual(facets.time_band(rec), "two-weeks")
# cross-country is slower: 12 to 20 km a day
rec = fake(2, km=300, hike={"travel": "mostly-cross-country"})
self.assertEqual(facets.time_days(rec), (15, 25, True))
self.assertIn("12 to 20 km", facets.estimate_note(rec))
self.assertEqual(facets.time_band(rec), "month")
def test_every_trail_has_a_time_and_its_label(self):
for rec in records.load_records(ROOT):
lo, hi, est = facets.time_days(rec)
self.assertTrue(0 < lo <= hi, rec["id"])
self.assertIn(facets.time_band(rec), facets.TIME_LABEL, rec["id"])
self.assertEqual(bool(facets.estimate_note(rec)), est, rec["id"])
row = text(home.entry(fake(1, km=300)))
self.assertIn("About 1 to 2 weeks estimate", row)
self.assertNotIn("estimate", text(home.entry(fake(1, hike={"days": [4, 6]}))))
def test_bands(self):
self.assertEqual(facets.time_band(fake(1, hike={"days": [5, 8]})), "week") # middle 6.5 days
self.assertEqual(facets.time_band(fake(1, hike={"days": [7, 21]})), "two-weeks")
self.assertEqual(facets.time_band(fake(1, hike={"days": [20, 35]})), "month")
class PlaceTest(unittest.TestCase):
def test_every_code_in_exactly_one_group(self):
keys = [k for _, _, ks in facets.PLACE_GROUPS for k in ks]
self.assertEqual(len(keys), len(set(keys)))
every = {f"US-{c}" for c in words.US_STATES} | {f"CA-{c}" for c in words.CA_PROVINCES}
self.assertEqual(set(keys), every)
def test_every_code_the_records_use(self):
for rec in records.load_records(ROOT):
keys = facets.place_keys(rec)
self.assertTrue(keys, rec["id"])
for key in keys:
self.assertTrue(key in facets.GROUP_OF or key == facets.ACROSS_CANADA, f"{rec['id']}: {key}")
self.assertTrue(facets.place_groups(rec), rec["id"])
def test_tokens(self):
rec = fake(1, regions=["AZ", "NM"])
self.assertEqual(facets.where_tokens(rec), ["US", "US-AZ", "US-NM", "g:southwest"])
across = fake(2, regions=[words.ALL_CANADA], country="CA")
self.assertEqual(facets.place_keys(across), ["CA-*"])
self.assertEqual(set(facets.place_groups(across)),
{"north", "western-canada", "central-canada", "atlantic-canada"})
# a US trail that names a province is in that province's group
ect = fake(3, regions=["ME", "QC", "NB"])
self.assertEqual(facets.place_keys(ect), ["US-ME", "CA-QC", "CA-NB"])
self.assertIn("atlantic-canada", facets.place_groups(ect))
def test_breadcrumb_by_place(self):
body = trail.render(fake(1, regions=["CO"]), GH)[2]
crumbs = body[body.index('<nav class="breadcrumb"'):body.index("</nav>")]
self.assertIn('<a href="/regions/">Places</a>', crumbs)
self.assertIn('<a href="/regions/#mountain-west">Mountain West</a>', crumbs)
self.assertIn('<a href="/regions/us-co/">Colorado</a>', crumbs)
class MissingValuesTest(unittest.TestCase):
def recs(self, n_with, n_without):
return ([fake(i, hike={"months": [7, 8], "season": "July and August", "terrain": ["alpine"]})
for i in range(n_with)] + [fake(100 + i) for i in range(n_without)])
def test_coverage_threshold(self):
self.assertTrue(facets.offered(self.recs(4, 8), "season")) # one third: offered
self.assertFalse(facets.offered(self.recs(3, 8), "season")) # less: not offered
form = home.finder_form(self.recs(3, 8))
self.assertNotIn('name="month"', form)
self.assertNotIn('name="terrain"', form)
form = home.finder_form(self.recs(4, 8))
self.assertIn('name="month"', form)
self.assertIn('name="terrain"', form)
def test_missing_count_is_said(self):
form = home.finder_form(self.recs(10, 12))
self.assertIn('data-missing="season" hidden>12 trails have no season on file.', form)
self.assertIn('data-missing="terrain" hidden>12 trails have no terrain on file.', form)
self.assertEqual(facets.missing_text(1, "season"), "1 trail has no season on file.")
self.assertEqual(facets.missing_text(0, "season"), "")
# full coverage: no note
self.assertNotIn('data-missing="season"', home.finder_form(self.recs(5, 0)))
def test_rows_without_a_value_carry_none(self):
# the script leaves out a row whose data-months is empty while a month is chosen
row = home.entry(fake(1))
self.assertIn('data-months=""', row)
self.assertIn('data-terrain=""', row)
row = home.entry(fake(1, hike={"months": [7, 8, 9]}))
self.assertIn('data-months="7 8 9"', row)
def test_script_leaves_out_missing_values(self):
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
js = f.read()
self.assertIn("if (s.month && words(d.months).indexOf(s.month) === -1) return false;", js)
self.assertIn("note.hidden = !on[note.dataset.missing]", js)
# Words that must not appear on a browsing page (home, places, lists, Routes, and a
# trail page above "About this data"). Record text can say what it likes; these are
# the site's own words, so they are checked in the site's own markup: headings,
# labels, legends, buttons, counts, empty states, alt text and descriptions.
BANNED = (r"\btrails and routes\b", r"\bperson-defined\b", r"\bways in\b", r"\bcollections?\b",
r"\brecord only\b", r"\bregions\b", r"\btrack polic(y|ies)\b", r"\btier\b", r"\bheld\b",
r"\bsource status\b", r"\bverification\b", r"\blisting\b", r"\bcreator\b", r"\bmaker\b",
r"\brecords?\b", r"\bentry\b", r"\bdesignated trail\b")
def site_words(doc):
"""The text the site writes on a page, without the trails' own text: rows' descriptions,
names, summaries and the record-sourced notes are dropped, and so is "About this data"."""
if '<details class="about-data"' in doc:
doc = doc[:doc.index('<details class="about-data"')]
doc = doc[doc.index('<main id="main">'):]
for cls in ("entry__desc", "entry__name", "trail-lede", "titleblock__sub", "entry__partial",
"note", "record-text", "map__reason", "glance__warn", "shelf__items", "onward__list"):
doc = re.sub(rf'<(\w+) class="{cls}"[^>]*>.*?</\1>', " ", doc, flags=re.S)
doc = re.sub(r"<dd>.*?</dd>", " ", doc, flags=re.S) # glance values are the trail's facts
doc = re.sub(r'<div class="notice notice--partial">.*?</div>', " ", doc, flags=re.S) # quotes the record
doc = re.sub(r'<li class="guide">.*?</li>', " ", doc, flags=re.S)
doc = re.sub(r'<a [^>]*href="(?:https?:|/trails/)[^"]*"[^>]*>.*?</a>', " ", doc, flags=re.S)
attrs = " ".join(re.findall(r'(?:alt|aria-label|title|placeholder|content)="([^"]*)"', doc))
return html.unescape(re.sub(r"<[^>]+>", " ", doc) + " " + attrs)
class BuiltVocabularyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
def read(self, rel):
with open(os.path.join(OUT, *rel.split("/")), encoding="utf-8") as f:
return f.read()
def browsing_pages(self):
rels = ["index.html", "regions/index.html", "lists/index.html", "routes/index.html", "404.html"]
for d in ("regions", "lists"):
for name in sorted(os.listdir(os.path.join(OUT, d))):
if os.path.isfile(os.path.join(OUT, d, name, "index.html")):
rels.append(f"{d}/{name}/index.html")
rels += [f"trails/{t}/index.html" for t in sorted(os.listdir(os.path.join(OUT, "trails")))
if os.path.isfile(os.path.join(OUT, "trails", t, "index.html"))]
return rels
def test_no_banned_word_on_a_browsing_page(self):
bad = []
for rel in self.browsing_pages():
words_ = site_words(self.read(rel))
for pattern in BANNED:
m = re.search(pattern, words_, re.I)
if m:
bad.append((rel, m.group(0), words_[max(0, m.start() - 40):m.end() + 40]))
self.maxDiff = None
self.assertEqual(bad[:40], [])
def test_navigation_has_three_items(self):
doc = self.read("index.html")
nav = re.search(r'<nav aria-label="Main"><ul class="nav">(.*?)</ul></nav>', doc).group(1)
self.assertEqual(re.findall(r">([^<]+)</a>", nav), ["Trails", "Places", "About"])
def test_one_count_noun(self):
doc = self.read("index.html")
n = len(re.findall(r'<li class="entry" ', doc))
self.assertEqual(n, len(records.load_records(ROOT)))
self.assertIn(f"<strong>{n}</strong> of {n} trails", doc)
self.assertIn(f"{n} long-distance trails", doc)
def test_route_badges_link_to_the_routes_list(self):
for rel in ("index.html", "routes/index.html"):
doc = self.read(rel)
for m in re.finditer(r'<(\w+) class="tag tag--route"([^>]*)>Route<', doc):
self.assertEqual((m.group(1), m.group(2)), ("a", ' href="/routes/"'), rel)
def test_old_urls_still_built(self):
recs = records.load_records(ROOT)
paths = ["index.html", "regions/index.html", "routes/index.html", "about/index.html", "data/index.html",
"data/schema/index.html", "data/changelog/index.html", "sources/index.html",
"logos/index.html", "404.html", "data/trails.csv", "data/trails.json", "data/index.geojson",
"data/overview.geojson", "data/all-gpx.zip", "data/all-geojson.zip", "licences/LICENSE"]
paths += [f"trails/{r['id']}/index.html" for r in recs]
paths += [f"trails/{r['id']}/trail.toml" for r in recs]
for key in {k for r in recs for k in facets.place_keys(r) if k != facets.ACROSS_CANADA}:
paths.append(f"regions/{key.lower()}/index.html")
for rel in paths:
self.assertTrue(os.path.isfile(os.path.join(OUT, *rel.split("/"))), rel)
def test_about_holds_the_dataset_terms(self):
doc = self.read("about/index.html")
for want in ('id="how-trails-are-chosen"', "Held", "Deferred", "Candidate", "Track policy",
'href="/data/"', 'href="/sources/"', 'href="/logos/"', 'id="correct-or-add"'):
self.assertIn(want, doc, want)
for rel in ("data/index.html", "sources/index.html", "logos/index.html", "data/schema/index.html"):
self.assertIn('<li><a href="/about/">About</a></li>', self.read(rel), rel)
def test_trail_page_ways_onward(self):
doc = self.read("trails/sierra-high-route/index.html")
foot = doc[doc.index('<nav class="onward"'):doc.index('<details class="about-data"')]
self.assertIn("More in California", foot)
doc = self.read("trails/kings-canyon-high-basin-route/index.html")
self.assertIn("More routes by Andrew Skurka", doc)
self.assertIn('href="/trails/yosemite-high-route/"', doc[doc.index('<nav class="onward"'):])
if __name__ == "__main__":
unittest.main()
+319
View File
@@ -0,0 +1,319 @@
"""Tests for the hiker's part of the site: the [hike] facts on a trail page, the
"About this data" part, the words on the browsing surfaces, and the home page's
collections (olt/hike.py, olt/browse.py, olt/trail.py, olt/home.py).
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__)))
sys.path.insert(0, WEB)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from olt import browse, hike, home, site, trail, words # noqa: E402
from test_pages import sample_record # noqa: E402
GH = site.Site("N", "T", repo_url="https://github.com/o/r")
FULL_HIKE = {
"summary": "A long walk along the crest of the Example Range. It crosses three passes. Water is scarce in Mt. Dry country.",
"official_url": "https://trail.example/",
"start": "South Gate, Arizona",
"end": "North Gate, Utah",
"shape": "point-to-point",
"days": [150, 210],
"season": "March to October",
"high_point": "Example Peak",
"high_point_m": 2025,
"terrain": ["forest", "alpine"],
"permit": "A permit is needed for the national park section",
"unfinished": "Forty miles are still on roads",
"checked": "2026-11-13",
"source": [{"url": "https://trail.example/facts", "publisher": "Example Trail Association",
"facts": ["start", "end", "days", "season"]}],
}
def with_line(rec):
"""A fixture record with a track and its downloads, so the download panel is drawn."""
rec = copy.deepcopy(rec)
rec["source"].update({"status": "verified", "licence": "CC-BY-4.0", "attribution": "Example Trail Association (CC BY 4.0)",
"line_source": "Example Trail Association", "line_file": "line.geojson",
"line_absent_reason": ""})
rec["verification"] = {"verified": True, "date": "2026-11-10", "measured_km": 60.0,
"difference_percent": -40.0, "parts": 3, "note": "Only part is built."}
rec["source"]["length_gap_note"] = "The trail is not finished."
rec["derived"].update({"has_line": True, "status": "included", "files": {"line": "x/line.geojson"},
"downloads": [{"role": "main", "format": "GPX", "file": "x.gpx", "bytes": 1000},
{"role": "main", "format": "GeoJSON", "file": "x.geojson", "bytes": 3000}]})
return rec
def render(rec, s=GH):
return trail.render(rec, s)[2]
def top_part(body):
"""The hiker's part of a trail page: everything before "About this data"."""
return body[:body.index('<details class="about-data"')]
def text(fragment):
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment)))
DATASET_WORDS = ("record", "Record", "tier", "Tier", "Held", "held", "Deferred", "Candidate", "wave",
"person-defined", "Person-defined", "track policy", "Track policy", "creator", "Creator",
"maker", "listing", "Listing", "collection", "Collection", "Ways in", "trails and routes",
"Trails and routes", "record only", "source status", "Source status", "verification",
"Verification", "line", "Line", "Regions", "entry")
class FormatTest(unittest.TestCase):
def test_days(self):
cases = {(4, 6): "4 to 6 days", (1, 1): "1 day", (5, 5): "5 days", (10, 14): "10 to 14 days",
(14, 21): "2 to 3 weeks", (20, 35): "3 to 5 weeks", (21, 21): "about 3 weeks",
(150, 210): "5 to 7 months", (40, 70): "1 to 2 months", (180, 180): "about 6 months"}
for days, want in cases.items():
self.assertEqual(words.fmt_days(list(days)), want, days)
self.assertEqual(words.fmt_days(7), "7 days")
self.assertEqual(words.fmt_days([]), "")
self.assertEqual(words.fmt_days(None), "")
def test_elevation_follows_the_unit_toggle(self):
e = str(words.elevation(2025))
# the same km/mi pair as lengths, so html[data-units] orders metres and feet too
self.assertIn('<span class="len__km">2,025 m</span>', e)
self.assertIn('<span class="len__mi">6,644 ft</span>', e)
self.assertIn('class="len len--inline"', e)
def test_first_sentence(self):
self.assertEqual(hike.first_sentence("One. Two."), "One.")
self.assertEqual(hike.first_sentence("Past Mt. Hood and St. Helens. Then on."), "Past Mt. Hood and St. Helens.")
self.assertEqual(hike.first_sentence("By J. Smith in 1970. More."), "By J. Smith in 1970.")
self.assertEqual(hike.first_sentence("Only one"), "Only one")
class TrailPageTest(unittest.TestCase):
def test_full_hike_table(self):
rec = sample_record("X Trail")
rec["hike"] = copy.deepcopy(FULL_HIKE)
top = top_part(render(rec))
t = text(top)
self.assertIn("A long walk along the crest of the Example Range. It crosses three passes.", t)
self.assertIn('href="https://trail.example/"', top)
self.assertIn("Official site", t)
for want in ("Time 5 to 7 months", "Season March to October", "Example Peak",
"2,025 m", "6,644 ft", "Shape End to end. South Gate, Arizona to North Gate, Utah",
"Terrain Forest, Alpine", "Permits A permit is needed for the national park section.",
"Not finished. Forty miles are still on roads."):
self.assertIn(want, t, want)
self.assertNotIn("Estimated from the length", t) # a source states the time
self.assertIn("Walking is not on file for this trail yet.", t)
# where the facts were read: in "About this data", with the facts in plain words
about = render(rec)[render(rec).index('<details class="about-data"'):]
self.assertIn("Where the hiking facts come from", about)
self.assertIn('href="https://trail.example/facts"', about)
self.assertIn("For start, end, time and season", text(about))
self.assertIn("Checked 2026-11-13.", text(about))
self.assertEqual(trail.description(rec)[:52], "A long walk along the crest of the Example Range. Wh")
def test_partial_hike_table(self):
rec = sample_record("X Trail")
rec["hike"] = {"shape": "loop", "start": "Lake Camp", "days": [4, 6], "checked": "2026-11-13"}
top = top_part(render(rec))
t = text(top)
self.assertIn("Shape Loop. Starts and ends at Lake Camp", t)
self.assertIn("Time 4 to 6 days", t)
self.assertIn("Season, terrain and walking are not on file for this trail yet.", t)
for absent in ("Season March", "High point", "Terrain Alpine", "Permits", "Not finished", "Official site"):
self.assertNotIn(absent, t, absent)
# no summary: the lede is built from the record
self.assertIn("A trail of 100 km 62 mi in Arizona, United States.", t)
about = render(rec)[render(rec).index('<details class="about-data"'):]
self.assertIn("The record names no page for these facts.", about)
def test_no_hike_table(self):
rec = sample_record("X Trail")
body = render(rec)
top = top_part(body)
t = text(top)
self.assertIn("A trail of 100 km 62 mi in Arizona, United States.", t)
self.assertIn("Length", t)
self.assertIn("Where Arizona , United States", t)
# every trail has a time: here estimated from its 100 km, and labelled so
self.assertIn("Time About 4 to 5 days Estimated from the length, at 20 to 30 km (12 to 19 mi) a day.", t)
self.assertIn("Season, terrain and walking are not on file for this trail yet.", t)
self.assertNotIn("Where the hiking facts come from", body)
# no track: the page says so plainly and points at the source
self.assertIn("No GPX here", t)
self.assertIn("GPX Not here, see the official site", t)
self.assertIn('href="#track"', top)
self.assertIn('id="track"', top)
def test_top_of_page_uses_plain_words(self):
for hike_table in (None, FULL_HIKE):
for rec in (sample_record("X Trail"), with_line(sample_record("X Trail"))):
rec = copy.deepcopy(rec)
rec["wave"] = "held"
rec["tier"] = "deferred"
if hike_table:
rec["hike"] = copy.deepcopy(hike_table)
t = text(top_part(render(rec)))
for word in DATASET_WORDS:
self.assertNotRegex(t, rf"\b{word}", word)
def test_about_this_data_is_collapsed_and_complete(self):
rec = with_line(sample_record("X Trail"))
body = render(rec)
about = body[body.index('<details class="about-data"'):]
self.assertTrue(about.startswith('<details class="about-data" id="about-data">')) # closed by default
for part in ('id="record-title"', 'id="verify-title"', 'id="source-title"', 'id="osm-title"',
'id="logo-title"', 'id="links-title"', 'id="correct-title"', '<details class="rawrecord">'):
self.assertIn(part, about, part)
self.assertNotIn(part, top_part(body), part)
def test_credit_licence_and_partial_warning_stay_in_view(self):
rec = with_line(sample_record("X Trail"))
top = top_part(render(rec))
# the credit and licence beside the downloads, and on the map's caption
panel = top[top.index('id="download"'):]
self.assertIn('id="credit-text">Example Trail Association (CC BY 4.0)<', panel)
self.assertIn('Licence: <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>', panel)
self.assertLess(panel.index('<ul class="downloads">'), panel.index('class="credit"'))
caption = top[top.index('<figcaption class="mapfig__caption">'):]
self.assertIn("Credit: Example Trail Association (CC BY 4.0).", caption)
# the partial warning above the buttons, and in the glance
self.assertLess(panel.index("notice--partial"), panel.index('<ul class="downloads">'))
self.assertIn("Partial GPX to download here", top)
self.assertIn("Track measures 60.0 km of 100 km published", text(top))
def test_report_a_problem_stays_in_view(self):
top = top_part(render(sample_record("X Trail")))
self.assertIn('>Report a problem</a>', top)
self.assertIn("template=correction.yml", top)
self.assertIn("Not for navigation", top)
# without a repository there is nothing to link
self.assertNotIn("Report a problem", top_part(render(sample_record("X Trail"), site.Site("N", "T"))))
def fake(i, km=100, **kw):
rec = sample_record(f"T{i}")
rec["id"] = f"t{i}"
rec["length_km"] = km
rec["derived"] = dict(rec["derived"])
for k, v in kw.items():
if k == "hike":
rec["hike"] = v
elif k == "tier":
rec["tier"] = v
elif k == "line":
rec["derived"]["has_line"] = v
elif k == "regions":
rec["regions"] = v
elif k == "country":
rec["country"] = v
return rec
def by_key(key):
return browse.by_key(key)
class ListTest(unittest.TestCase):
def test_each_rule(self):
route = fake(1)
route["derived"]["kind"] = "route"
cases = {
"national-scenic-trails": (fake(1, tier="national"), fake(2)),
"routes": (route, fake(2)),
"longest": (fake(1, km=2000), fake(2, km=1999)),
"under-100-km": (fake(1, km=99), fake(2, km=100)),
# by Time: stated, or estimated from the length
"a-week-or-less": (fake(1, hike={"days": [4, 7]}), fake(2, hike={"days": [20, 35]})),
"one-to-two-weeks": (fake(1, km=250), fake(2, km=100)),
"loops": (fake(1, hike={"shape": "loop"}), fake(2, hike={"shape": "point-to-point"})),
"with-gpx": (fake(1, line=True), fake(2)),
"canada": (fake(1, regions=["ON"], country="CA"), fake(2)),
"united-states": (fake(1), fake(2, regions=["ON"], country="CA")),
"off-trail": (fake(1, hike={"travel": "some-cross-country"}), fake(2, hike={"travel": "trail-and-road"})),
"terrain-desert": (fake(1, hike={"terrain": ["desert"]}), fake(2, hike={"terrain": ["forest"]})),
}
for key, (inside, outside) in cases.items():
lst = by_key(key)
self.assertTrue(lst.test(inside), key)
self.assertFalse(lst.test(outside), key)
self.assertTrue(by_key("a-week-or-less").test(fake(3, km=100))) # 4 to 5 days, estimated
# a trail without [hike] is in no list that needs a [hike] fact
for key in ("loops", "terrain-alpine", "off-trail"):
self.assertFalse(by_key(key).test(fake(3)), key)
def test_paths(self):
self.assertEqual(browse.path(by_key("routes")), "/routes/")
self.assertEqual(browse.path(by_key("loops")), "/lists/loops/")
def test_threshold(self):
self.assertFalse(browse.is_shown(browse.MIN_SIZE - 1, 100))
self.assertTrue(browse.is_shown(browse.MIN_SIZE, 100))
self.assertTrue(browse.is_shown(75, 100))
self.assertFalse(browse.is_shown(76, 100))
def test_thin_list_is_not_shown(self):
# three loops among twenty trails: below MIN_SIZE, so no link and no page
recs = [fake(i, hike={"shape": "loop"} if i < 3 else {"shape": "point-to-point"}) for i in range(20)]
for i in range(5):
recs[i]["tier"] = "national"
keys = [lst.key for lst, _ in browse.shown(recs)]
self.assertNotIn("loops", keys)
self.assertIn("national-scenic-trails", keys)
self.assertNotIn("united-states", keys) # every one of them: nearly everything
body = home.render(recs, GH)
self.assertNotIn('href="/lists/loops/"', body)
self.assertIn('href="/lists/national-scenic-trails/"', body)
recs[3]["hike"] = {"shape": "loop"}
self.assertIn("loops", [lst.key for lst, _ in browse.shown(recs)])
def test_rules_name_no_trail(self):
ids = [d for d in os.listdir(os.path.dirname(WEB)) if os.path.isfile(os.path.join(os.path.dirname(WEB), d, "trail.toml"))]
for name in ("browse.py",):
with open(os.path.join(WEB, "olt", name), encoding="utf-8") as f:
source = f.read()
for tid in ids:
self.assertNotIn(f'"{tid}"', source, f"{name}: {tid}")
class ListRowTest(unittest.TestCase):
def test_row_words_and_description(self):
rec = fake(1)
rec["wave"] = "held"
rec["tier"] = "deferred"
row = home.entry(rec)
t = text(row)
for word in DATASET_WORDS:
self.assertNotRegex(t, rf"\b{word}", word)
self.assertIn("See the official site", t)
rec["hike"] = {"summary": "A fine walk. Long too.", "days": [4, 6]}
t = text(home.entry(rec))
self.assertIn("A fine walk.", t)
self.assertNotIn("Long too.", t)
self.assertIn("4 to 6 days", t)
def test_route_rows_say_how_to_get_the_track(self):
rec = fake(1)
rec["derived"]["kind"] = "route"
rec["kind"] = "route"
rec["route"] = {"creator": "A Person", "line_policy": "sold"}
rec["guide"] = []
self.assertIn("Sold by its author", text(home.entry(rec)))
self.assertIn("Route by A Person", text(home.entry(rec)))
self.assertIn('<a class="tag tag--route" href="/routes/">Route</a>', home.entry(rec))
self.assertNotRegex(text(home.entry(rec)), r"\b(creator|maker|person-defined)\b")
if __name__ == "__main__":
unittest.main()
+16 -9
View File
@@ -190,9 +190,13 @@ class BuiltSiteTest(unittest.TestCase):
f"{rec['length_km']:,} km ({words.fmt_percent(v['difference_percent'])})", text)
self.assertIn(re.sub(r"\s+", " ", rec["source"]["length_gap_note"]), text, rec["id"])
short = rec["id"] in expected and rec["verification"]["difference_percent"] < 0
self.assertEqual("In the dataset, partial" in page, short, rec["id"])
glance = page[page.index('<section class="glance'):page.index("</section>", page.index('<section class="glance'))]
self.assertEqual("Partial GPX to download here" in glance, short, rec["id"])
if rec["derived"]["has_line"]:
self.assertRegex(page, r'<dt>Track</dt><dd><a href="#download">In the dataset', rec["id"])
self.assertRegex(glance, r'<dt>GPX</dt><dd><a href="#download">(Partial )?GPX to download here</a>', rec["id"])
# the partial warning is in view, outside "About this data"
if rec["id"] in expected:
self.assertLess(page.index("notice--partial"), page.index('<details class="about-data"'), rec["id"])
rows_seen = set()
for path in html_files(OUT):
with open(path, encoding="utf-8") as f:
@@ -257,17 +261,20 @@ class BuiltSiteTest(unittest.TestCase):
def test_no_raw_tokens_in_the_main_flow(self):
for rec in self.records:
page = self.pages[rec["id"]]
main = page[page.index('<div class="detail__main">'):page.index('<details class="rawrecord">')]
top = page[page.index('<main id="main">'):page.index('<details class="about-data"')]
self.assertNotIn('<code class="raw">', top, rec["id"])
main = page[page.index('<div class="about-data__body'):page.index('<details class="rawrecord">')]
codes = set(html.unescape(c) for c in re.findall(r'<code class="raw">(.*?)</code>', main))
self.assertLessEqual(codes, {rec["id"]}, rec["id"])
# main-column sections are not landmarks; the aside panels are
# "About this data" sections are not landmarks; the glance and the aside panels are
self.assertNotIn('<section class="block" aria-labelledby', page, rec["id"])
self.assertIn('<section class="panel" aria-labelledby="links-title">', page, rec["id"])
self.assertIn('<section class="glance detail__glance" aria-labelledby="glance-title">', page, rec["id"])
self.assertIn('<h2 id="links-title">Links</h2>', main, rec["id"])
def test_record_without_a_line_says_so_once(self):
for rec in self.records:
page = self.pages[rec["id"]]
main = page_text(page[page.index('<div class="detail__main">'):page.index('<details class="rawrecord">')])
main = page_text(page[page.index('<div class="about-data__body'):page.index('<details class="rawrecord">')])
helper = "Where to ask for the track: a layer or relation page"
if rec["derived"]["has_line"]:
self.assertEqual(helper in main, bool(rec["source"].get("url")), rec["id"])
@@ -481,9 +488,9 @@ class RenderUnitTest(unittest.TestCase):
f.write('id = "x"\n')
rec = sample_record(name="A & B")
n = pages.render_site([rec], out, repo, site=site.Site("N", "T"))
# trail page + home + 404 + regions index + 1 region + routes,
# sources, logos, about, data, schema, changelog
self.assertEqual(n, 12)
# trail page + home + 404 + places hub + 1 place + lists hub + routes,
# sources, logos, about, data, schema, changelog (no list holds MIN_SIZE trails)
self.assertEqual(n, 13)
with open(os.path.join(out, "trails", "x", "index.html"), encoding="utf-8") as f:
self.assertIn("A &amp; B", f.read())
with open(os.path.join(out, "index.html"), encoding="utf-8") as f: