Make a trail's length one end-to-end walk, and put the map and the trails in the first screen
Lengths and what belongs: - A trail's length is now the end-to-end length of its canonical path: one branch at a split, no side trails, no system totals. A holder's larger figure and the built length of an unfinished trail are separate fields (`system_km`, `system_note`, `built_km`), shown under the length. - Corrected: Florida Trail 1,500 to 1,130 mi, American Discovery Trail 6,800 to 5,008 mi, Ozark Trail to 230 mi, General Crook Trail to 138 mi, Sheltowee Trace to 343 mi, Allegheny Trail to 316 mi, Great Eastern Trail to 1,800 mi. - The Florida Trail's and the Ice Age Trail's main tracks are re-cut as one walk; the other branches are alternates. - A trail must be walkable from end to end today. Nine trails that are not, are a network, or fall under the floor move to the "Considered and left out" list. The Bayou State Trail is added. 196 trails. Pages: - The trail page puts the map and At a glance directly under the title; the home page drops its oversized hero and shows the trails and the map at once. Place and list pages put the list beside the map. - Every map starts by itself once the page is ready, over a drawing of the tracks that is in the page from the first paint. - Lists is in the header. The home page shows ten lists chosen in `collections.toml`. Tables have equal columns and stack on a phone. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
No files matched your search
@@ -4,13 +4,15 @@
|
||||
early by prefs.js), and the theme menu in the header
|
||||
1b. Saved trails: the Save buttons, the count in the header (lh-saved in localStorage)
|
||||
1c. The Saved page (/saved/): the visitor's saved trails, or a list from a link
|
||||
2. Maps: .mapfig[data-map] figures. Nothing for a map is loaded with the page: when
|
||||
the figure scrolls near the screen (or is touched, or takes focus) the script
|
||||
loads MapLibre (and the contour add-on) from the addresses on its own <script>
|
||||
tag, and fetches the figure's data from data-src (same origin). Lines are drawn
|
||||
on a plain graticule first, then on an OpenFreeMap base map when MapLibre and
|
||||
WebGL are available. A trail page's map (data-outdoor) is an outdoor map, with
|
||||
relief and contours, and a switch to the plain one.
|
||||
2. Maps: .mapfig[data-map] figures. A frame is never empty: the page carries a static
|
||||
drawing of its tracks (olt/sketch.py). A moment after the page has loaded (idle, or
|
||||
after 500 ms at most), and never on a scroll, a touch, a key or focus, every map starts
|
||||
by itself: the script loads MapLibre (and the contour add-on) from the addresses on its
|
||||
own <script> tag, and fetches the figure's data
|
||||
from data-src (same origin). The live map opens on the same ground as the drawing
|
||||
(data-frame), and the drawing gives way to it once it has drawn the tracks. Where
|
||||
the base map cannot load, the drawing stays. A trail page's map (data-outdoor) is an
|
||||
outdoor map, with relief and contours, and a switch to the plain one.
|
||||
3. Trail finder (home page): search, filters, sort, URL query state, map/list highlight
|
||||
4. Copy-credit buttons
|
||||
|
||||
@@ -636,13 +638,9 @@
|
||||
return d + '°' + (m < 10 ? '0' : '') + m + '′' + (value >= 0 ? pos : neg);
|
||||
}
|
||||
|
||||
/* Lines on a plain graticule (Web Mercator), no tiles. Returns the drawn extent. */
|
||||
function drawFallback(host, fc, bbox, routeMain) {
|
||||
bbox = ensureSpan(bbox);
|
||||
var rect = host.getBoundingClientRect();
|
||||
var W = Math.max(Math.round(rect.width), 280);
|
||||
var H = Math.max(Math.round(rect.height), 180);
|
||||
var pad = 28;
|
||||
/* The ground a W x H frame shows when it fits bbox with pad pixels around it (Web Mercator,
|
||||
as MapLibre's fitBounds does). */
|
||||
function extentOf(bbox, W, H, pad) {
|
||||
var rad = Math.PI / 180;
|
||||
var cx = (bbox[0] + bbox[2]) / 2;
|
||||
var y0 = mercY(bbox[1]);
|
||||
@@ -650,9 +648,20 @@
|
||||
var cy = (y0 + y1) / 2;
|
||||
var k = Math.min((W - 2 * pad) / Math.max((bbox[2] - bbox[0]) * rad, 1e-6),
|
||||
(H - 2 * pad) / Math.max(y1 - y0, 1e-6));
|
||||
return { cx: cx, cy: cy, k: k, rad: rad,
|
||||
w: cx - W / 2 / k / rad, e: cx + W / 2 / k / rad, n: invMercY(cy + H / 2 / k), s: invMercY(cy - H / 2 / k) };
|
||||
}
|
||||
|
||||
/* Lines on a plain graticule (Web Mercator), no tiles. Returns the drawn extent. */
|
||||
function drawFallback(host, fc, bbox, routeMain) {
|
||||
bbox = ensureSpan(bbox);
|
||||
var rect = host.getBoundingClientRect();
|
||||
var W = Math.max(Math.round(rect.width), 280);
|
||||
var H = Math.max(Math.round(rect.height), 180);
|
||||
var ext = extentOf(bbox, W, H, 28);
|
||||
var rad = ext.rad, cx = ext.cx, cy = ext.cy, k = ext.k;
|
||||
function x(lon) { return W / 2 + (lon - cx) * rad * k; }
|
||||
function y(lat) { return H / 2 - (mercY(lat) - cy) * k; }
|
||||
var ext = { w: cx - W / 2 / k / rad, e: cx + W / 2 / k / rad, n: invMercY(cy + H / 2 / k), s: invMercY(cy - H / 2 / k) };
|
||||
|
||||
var span = Math.max(ext.e - ext.w, ext.n - ext.s);
|
||||
var step = [0.25, 0.5, 1, 2, 5, 10, 15].filter(function (s) { return span / s <= 9; })[0] || 20;
|
||||
@@ -909,6 +918,19 @@
|
||||
|
||||
var bbox = (fig.dataset.bbox || '').split(',').map(Number);
|
||||
if (bbox.length !== 4 || bbox.some(isNaN)) bbox = null;
|
||||
/* The ground the static drawing shows, and the live map opens on with no padding of its own. */
|
||||
var frame = (fig.dataset.frame || '').split(',').map(Number);
|
||||
if (frame.length !== 4 || frame.some(isNaN)) frame = null;
|
||||
entry.frame = frame;
|
||||
entry.initialIds = onlyIds.length ? onlyIds : null;
|
||||
|
||||
/* The page's own drawing of the tracks (class map__sketch) stays until the live map has
|
||||
drawn its first frame. Until then nothing is redrawn over it. */
|
||||
function hasSketch() { return !!fallback.querySelector('.map__sketch'); }
|
||||
function say(text) {
|
||||
status.textContent = text;
|
||||
status.dataset.say = '1';
|
||||
}
|
||||
|
||||
function corners(ext) {
|
||||
/* A wide map of Alaska reaches past 180°: name that longitude as the east one it is. */
|
||||
@@ -916,7 +938,13 @@
|
||||
if (nw) nw.textContent = dms(ext.n, 'N', 'S') + ' ' + dms(wrap(ext.w), 'E', 'W');
|
||||
if (se) se.textContent = dms(ext.s, 'N', 'S') + ' ' + dms(wrap(ext.e), 'E', 'W');
|
||||
}
|
||||
function sketchCorners() {
|
||||
if (!frame || !hasSketch()) return;
|
||||
var r = host.getBoundingClientRect();
|
||||
if (r.width && r.height) corners(extentOf(frame, r.width, r.height, 0));
|
||||
}
|
||||
function redrawFallback() {
|
||||
if (hasSketch()) { sketchCorners(); return; }
|
||||
if (!entry.ready && entry.fc) {
|
||||
corners(drawFallback(fallback, entry.fc, bbox || bboxOf(entry.fc), routeMain));
|
||||
if (entry.visibleIds) setVisible(entry, entry.visibleIds);
|
||||
@@ -925,16 +953,15 @@
|
||||
function fail(reason) {
|
||||
if (entry.ready) return;
|
||||
host.dataset.state = 'fallback';
|
||||
status.textContent = 'Base map unavailable (' + reason + '). ' +
|
||||
(kind === 'sketch' ? 'The start and end are drawn on a plain graticule.' : 'The track is drawn on a plain graticule.');
|
||||
say('Base map unavailable (' + reason + '). ' +
|
||||
(kind === 'sketch' ? 'The start and end are drawn on a plain ground.' : 'The track is drawn on a plain ground.'));
|
||||
}
|
||||
|
||||
/* Until the map starts the frame holds its size (the CSS), with a note that
|
||||
says what happens next; the page loads nothing for it. */
|
||||
status.textContent = 'The map loads when you scroll to it.';
|
||||
/* Until the map starts the frame holds its size and its drawing (the page's own, or one
|
||||
made from the data); the page loads nothing more for it. */
|
||||
sketchCorners();
|
||||
var dataReady = null;
|
||||
function fetchData() {
|
||||
status.textContent = kind === 'sketch' ? 'Loading the map…' : 'Loading the track…';
|
||||
return fetch(fig.dataset.src, { credentials: 'same-origin' })
|
||||
.then(function (r) {
|
||||
if (!r.ok) throw new Error(r.status);
|
||||
@@ -956,13 +983,12 @@
|
||||
: fb;
|
||||
});
|
||||
}
|
||||
if (!entry.ready && entry.mapStarted && window.maplibregl) status.textContent = 'Loading the base map…';
|
||||
redrawFallback();
|
||||
return fc;
|
||||
})
|
||||
.catch(function () {
|
||||
host.dataset.state = 'error';
|
||||
status.textContent = 'The track data did not load. Downloads on this page are unaffected.';
|
||||
say('The track data did not load. Downloads on this page are unaffected.');
|
||||
return null;
|
||||
});
|
||||
}
|
||||
@@ -980,7 +1006,6 @@
|
||||
function startMapLibre() {
|
||||
if (!window.maplibregl) { dataReady.then(function (fc) { if (fc) fail('the map library did not load'); }); return; }
|
||||
if (!webglAvailable()) { dataReady.then(function (fc) { if (fc) fail('WebGL is off in this browser'); }); return; }
|
||||
if (!entry.ready && entry.fc) status.textContent = 'Loading the base map…';
|
||||
var timer = setTimeout(function () { fail('tiles did not load'); }, 15000);
|
||||
if (outdoorUrl) fetchOutdoor(outdoorUrl).then(function (base) { createMap(base, timer); });
|
||||
else createMap(null, timer);
|
||||
@@ -1003,7 +1028,12 @@
|
||||
pitchWithRotate: false,
|
||||
touchPitch: false
|
||||
};
|
||||
if (bbox) {
|
||||
if (frame) {
|
||||
/* The ground the page's drawing shows, fitted with no padding of its own: the track
|
||||
does not move when the live map takes over. */
|
||||
options.bounds = [[frame[0], frame[1]], [frame[2], frame[3]]];
|
||||
options.fitBoundsOptions = { padding: 0 };
|
||||
} else if (bbox) {
|
||||
options.bounds = [[bbox[0], bbox[1]], [bbox[2], bbox[3]]];
|
||||
options.fitBoundsOptions = { padding: 32 };
|
||||
}
|
||||
@@ -1070,8 +1100,27 @@
|
||||
}
|
||||
entry.ready = true;
|
||||
settled = true;
|
||||
host.dataset.state = 'ready';
|
||||
status.textContent = '';
|
||||
/* The live map shows (and the drawing gives way, in the CSS) once it has drawn its first
|
||||
frame with the tracks: the base map fills in behind a track that holds still. */
|
||||
var shown = false;
|
||||
function reveal() {
|
||||
if (shown) return;
|
||||
shown = true;
|
||||
host.dataset.state = 'ready';
|
||||
status.textContent = '';
|
||||
delete status.dataset.say;
|
||||
}
|
||||
/* Once the tracks' source is loaded and the map has drawn a frame since: the base map
|
||||
is still filling in, and the tracks it draws are where the drawing's were. */
|
||||
function trackDrawn() {
|
||||
if (!map.isSourceLoaded('olt')) return;
|
||||
map.off('sourcedata', trackDrawn);
|
||||
map.once('render', reveal);
|
||||
map.triggerRepaint();
|
||||
}
|
||||
map.on('sourcedata', trackDrawn);
|
||||
trackDrawn();
|
||||
setTimeout(reveal, 2500);
|
||||
collapseAttribution();
|
||||
if (entry.visibleIds) setVisible(entry, entry.visibleIds);
|
||||
if (kind === 'overview') wireOverview(entry, map, defs);
|
||||
@@ -1133,31 +1182,25 @@
|
||||
if (entry.mapStarted) return;
|
||||
entry.mapStarted = true;
|
||||
if (outdoorUrl) fetchOutdoor(outdoorUrl);
|
||||
dataReady = fetchData();
|
||||
dataReady = dataReady || fetchData();
|
||||
loadLibraries().then(startMapLibre);
|
||||
}
|
||||
|
||||
/* When: a fifth of the frame is on the screen and the page has loaded, or the
|
||||
moment it is touched, clicked or focused. A frame below the fold, or only
|
||||
peeking over it, costs the page nothing. A browser without
|
||||
IntersectionObserver starts it once the page has loaded. */
|
||||
/* When: every map starts by itself, once, a moment after the page has loaded: when the browser
|
||||
is idle, or after 500 ms at most. Where the map sits, how big the screen is, and whether the
|
||||
visitor scrolls, touches, types or does nothing make no difference. The drawing in the frame
|
||||
holds the place of the map until its first frame is drawn. */
|
||||
function afterLoad(fn) {
|
||||
if (document.readyState === 'complete') fn();
|
||||
else window.addEventListener('load', fn, { once: true });
|
||||
}
|
||||
['pointerdown', 'focusin', 'keydown'].forEach(function (type) {
|
||||
host.addEventListener(type, begin, { once: true, passive: true });
|
||||
afterLoad(function () {
|
||||
if (window.requestIdleCallback) requestIdleCallback(begin, { timeout: 500 });
|
||||
else setTimeout(begin, 100);
|
||||
});
|
||||
if ('IntersectionObserver' in window) {
|
||||
var watcher = new IntersectionObserver(function (changes) {
|
||||
if (!changes.some(function (c) { return c.isIntersecting; })) return;
|
||||
watcher.disconnect();
|
||||
afterLoad(begin);
|
||||
}, { threshold: 0.2 });
|
||||
watcher.observe(host);
|
||||
} else {
|
||||
afterLoad(begin);
|
||||
}
|
||||
/* A frame the page came without a drawing for (the saved trails, known only here) is drawn
|
||||
from the data as soon as this script has it. */
|
||||
if (!hasSketch()) dataReady = fetchData();
|
||||
}
|
||||
|
||||
function entryFor(id) {
|
||||
@@ -1239,8 +1282,13 @@
|
||||
if (!union) return;
|
||||
var target = shown >= total && entry.fullBounds ? entry.fullBounds : union;
|
||||
var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
var padding = 32;
|
||||
/* The trails the page opened on are the ground its drawing shows: that view needs no move. */
|
||||
var first = entry.initialIds || Object.keys(entry.boundsById);
|
||||
var same = ids.length === first.length && ids.every(function (id) { return first.indexOf(id) !== -1; });
|
||||
if (entry.frame && same) { target = entry.frame; padding = 0; }
|
||||
map.fitBounds([[target[0], target[1]], [target[2], target[3]]],
|
||||
{ padding: 32, maxZoom: 11, animate: !reduceMotion });
|
||||
{ padding: padding, maxZoom: 11, animate: !reduceMotion });
|
||||
}
|
||||
|
||||
function setVisible(entry, ids) {
|
||||
@@ -1252,6 +1300,10 @@
|
||||
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;
|
||||
/* The page's own drawing stands while the filters leave the trails it opened on. */
|
||||
var opened = entry.initialIds ? entry.initialIds.length : Object.keys(entry.boundsById || {}).length;
|
||||
var onSketch = entry.fallback.querySelector('.map__sketch');
|
||||
if (onSketch && ids.length === opened) { sub = []; }
|
||||
if (sub.length) drawFallback(entry.fallback, whole ? entry.fc : { type: 'FeatureCollection', features: sub },
|
||||
whole && entry.fullBounds ? entry.fullBounds : bboxOf({ features: sub }), false);
|
||||
}
|
||||
@@ -1269,7 +1321,7 @@
|
||||
fitToVisible(entry, ids);
|
||||
}
|
||||
|
||||
/* Each map waits for its moment (initMap): nothing is fetched here. The
|
||||
/* Each map starts by itself shortly after the page has loaded (initMap). The
|
||||
finder and the other controls below never wait for a map. */
|
||||
document.querySelectorAll('.mapfig[data-map]').forEach(initMap);
|
||||
|
||||
@@ -1439,6 +1491,16 @@
|
||||
var defaultSort = defaultSortOf(resultsRoot);
|
||||
var more = form.querySelector('.filters__more');
|
||||
var total = items.length;
|
||||
/* The bar: the Filters control opens the panels, and Clear shows only when something is set. */
|
||||
var toggle = form.querySelector('.filters__toggle');
|
||||
var panels = form.querySelector('.filters__panels');
|
||||
var clear = form.querySelector('.filters__clear');
|
||||
function showPanels(open) {
|
||||
if (!panels) return;
|
||||
if (open) panels.setAttribute('data-open', ''); else panels.removeAttribute('data-open');
|
||||
if (toggle) toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||||
}
|
||||
if (toggle) toggle.addEventListener('click', function () { showPanels(!panels.hasAttribute('data-open')); });
|
||||
|
||||
/* The count is the one live region. Keep it quiet through the first
|
||||
application below so nothing is announced on load, and write to it
|
||||
@@ -1671,7 +1733,9 @@
|
||||
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' : '');
|
||||
setText(form.querySelector('.filters__count'), all ? String(all) : '');
|
||||
/* Clear is offered only when something is set: a search, or any filter. */
|
||||
if (clear) clear.hidden = !(s.q || all);
|
||||
|
||||
maps.forEach(function (m) { if (m.kind === 'overview') setVisible(m, shown); });
|
||||
if (updateUrl) {
|
||||
@@ -1711,11 +1775,9 @@
|
||||
/* 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');
|
||||
/* The panels open from the bar; they start open when the address already sets a filter. */
|
||||
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;
|
||||
if (firstOn || MORE.some(function (name) { return s0[name].length; })) showPanels(true);
|
||||
window.addEventListener('popstate', function () { fromQuery(); applySort(); apply(false); });
|
||||
/* A page reached by Back, Forward or a reload: the browser may put the old
|
||||
values of the controls back after this script has run, or show an old copy
|
||||
@@ -1735,6 +1797,17 @@
|
||||
if (finder) initFinder(finder);
|
||||
initSortableLists();
|
||||
|
||||
/* 3b. A trail page's At a glance panel on a narrow screen: the button opens the rest of the facts. */
|
||||
document.querySelectorAll('[data-glance-toggle]').forEach(function (button) {
|
||||
var panel = button.closest('.glance');
|
||||
button.addEventListener('click', function () {
|
||||
var all = !panel.hasAttribute('data-all');
|
||||
if (all) panel.setAttribute('data-all', ''); else panel.removeAttribute('data-all');
|
||||
button.setAttribute('aria-expanded', all ? 'true' : 'false');
|
||||
button.textContent = all ? 'Fewer facts' : 'All the facts';
|
||||
});
|
||||
});
|
||||
|
||||
/* 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() {
|
||||
|
||||
@@ -287,11 +287,16 @@ html:not(.js) .site-header__inner { grid-template-areas: "mark mark" "nav nav";
|
||||
.wordmark:hover { text-decoration: none; }
|
||||
/* The mark: a mountain with a trail up it, the same file as the tab icon. */
|
||||
.wordmark__mark { inline-size: 1.75rem; block-size: 1.75rem; }
|
||||
/* The home page carries the name large in its hero, so the header does not repeat it. */
|
||||
body:has(.hero--home) .site-header .wordmark { visibility: hidden; }
|
||||
|
||||
.nav { display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-5); padding: 0; list-style: none; }
|
||||
@media (max-width: 30rem) { .nav { column-gap: var(--space-4); } }
|
||||
/* Five items now: between the narrow and the full header the gaps close up, so the links keep one
|
||||
row beside the name and the switches. */
|
||||
@media (min-width: 50rem) and (max-width: 63.99rem) {
|
||||
.site-header__inner { column-gap: var(--space-4); }
|
||||
.nav { column-gap: var(--space-4); }
|
||||
.prefs { padding-inline-start: var(--space-4); }
|
||||
}
|
||||
.nav a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -764,7 +769,13 @@ html:not(.js) .js-only { display: none !important; }
|
||||
.map__fallback svg { inline-size: 100%; block-size: 100%; }
|
||||
.map__canvas { opacity: 0; transition: opacity 0.4s ease; }
|
||||
.map[data-state="ready"] .map__canvas { opacity: 1; }
|
||||
.map[data-state="ready"] .map__fallback { visibility: hidden; }
|
||||
/* The page's drawing of the tracks gives way once the live map has drawn them: the map fades in
|
||||
over it, and the drawing is gone when the fade is done. */
|
||||
.map[data-state="ready"] .map__fallback { visibility: hidden; transition: visibility 0s 0.4s; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.map__canvas { transition: none; }
|
||||
.map[data-state="ready"] .map__fallback { transition: none; }
|
||||
}
|
||||
|
||||
.map__status {
|
||||
position: absolute;
|
||||
@@ -778,6 +789,8 @@ html:not(.js) .js-only { display: none !important; }
|
||||
font: 400 var(--step--2)/1.4 var(--font-sans);
|
||||
}
|
||||
.map[data-state="ready"] .map__status { display: none; }
|
||||
/* With JavaScript the note is for failures only; the no-script text is shown without it. */
|
||||
html.js .map__status:not([data-say]) { display: none; }
|
||||
|
||||
/* Fallback drawing: graticule and lines without tiles */
|
||||
.fallback__grat { stroke: var(--rule); stroke-width: 1; fill: none; vector-effect: non-scaling-stroke; }
|
||||
@@ -789,6 +802,13 @@ html:not(.js) .js-only { display: none !important; }
|
||||
.fallback__line--sketch-route { stroke: var(--route); }
|
||||
.fallback__ring { fill: var(--casing); stroke: var(--trail); stroke-width: 2; vector-effect: non-scaling-stroke; }
|
||||
.fallback__ring--route { stroke: var(--route); }
|
||||
/* The page's own drawing (olt/sketch.py): the widths the live map draws at the zoom it opens on. */
|
||||
.map__sketch .fallback__casing { stroke-width: 4; }
|
||||
.map__sketch .fallback__line { stroke-width: 2.5; }
|
||||
.map__sketch .fallback__line--alternate { stroke-width: 1.5; }
|
||||
.map__sketch .fallback__line--sketch { stroke-width: 2.5; }
|
||||
.mapfig[data-map="overview"] .map__sketch .fallback__line { stroke-width: 1.6; }
|
||||
.mapfig[data-map="overview"] .map__sketch .fallback__line--sketch { stroke-width: 2; }
|
||||
|
||||
.mapfig__caption {
|
||||
display: flex;
|
||||
@@ -932,26 +952,8 @@ html:not(.js) .js-only { display: none !important; }
|
||||
.hero__inner { position: relative; display: grid; gap: var(--space-5); }
|
||||
.hero h1 { max-inline-size: 28ch; font-size: var(--step-4); font-weight: 600; letter-spacing: -0.015em; }
|
||||
.hero__lede { max-inline-size: 40rem; font-size: var(--step-1); line-height: 1.5; }
|
||||
/* The home page's name plate: mark, name, what the site is, and what it offers. */
|
||||
.hero .lockup {
|
||||
display: flex; align-items: center; gap: clamp(0.75rem, 2.4vw, 1.75rem);
|
||||
max-inline-size: none;
|
||||
font-size: clamp(2.75rem, 1.2rem + 7vw, 6rem); font-weight: 600; line-height: 1; letter-spacing: -0.02em;
|
||||
}
|
||||
.lockup__mark { flex: none; inline-size: 1.15em; block-size: 1.15em; }
|
||||
.hero__tagline { max-inline-size: 26em; font: 400 var(--step-3)/1.25 var(--font-serif); }
|
||||
.hero__tags {
|
||||
display: flex; flex-wrap: wrap; gap: var(--space-1) 0; padding: 0; list-style: none;
|
||||
color: var(--ink-2); font: 600 var(--step-0)/1.4 var(--font-sans); letter-spacing: 0.09em; text-transform: uppercase;
|
||||
}
|
||||
/* Each item carries its dot on the left; the list is shifted and clipped by the
|
||||
same amount so a dot never starts a line. */
|
||||
.hero__tags { margin-inline-start: -1.7em; clip-path: inset(0 0 0 1.7em); }
|
||||
.hero__tags li { position: relative; padding-inline-start: 1.7em; }
|
||||
.hero__tags li::before { content: "\00B7"; position: absolute; inset-inline-start: 0.65em; }
|
||||
.hero__tags a { color: inherit; text-decoration: none; }
|
||||
.hero__tags a:hover { color: var(--ink); text-decoration: underline; text-underline-offset: 0.2em; }
|
||||
.hero--home .hero__lede { color: var(--ink-2); font-size: var(--step-0); }
|
||||
.hero--home h1 { max-inline-size: none; font-size: var(--step-3); line-height: 1.15; }
|
||||
.hero--home .hero__lede { color: var(--ink-2); font-size: var(--step-0); max-inline-size: none; }
|
||||
.hero__caveat {
|
||||
max-inline-size: 40rem;
|
||||
padding-inline-start: var(--space-4);
|
||||
@@ -962,50 +964,57 @@ html:not(.js) .js-only { display: none !important; }
|
||||
.hero__counts { display: grid; gap: var(--space-3); margin-block-start: var(--space-3); }
|
||||
.hero__cta { padding: var(--space-3) var(--space-5); font-size: var(--step-1); }
|
||||
|
||||
/* Finder: filters beside the results */
|
||||
.finder__grid {
|
||||
/* Home: the trails first. The lists, a search bar, then the trails, with the overview map beside
|
||||
them on a wide screen (it stays in view while the list scrolls). On a narrow screen the map
|
||||
follows the list, and the bar has a link to it. */
|
||||
.home {
|
||||
display: grid;
|
||||
gap: var(--space-5) var(--space-6);
|
||||
grid-template-areas: "filters" "main" "notes";
|
||||
gap: var(--space-1) var(--space-6);
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-areas: "lists" "bar" "results" "map" "notes";
|
||||
align-items: start;
|
||||
}
|
||||
.filters { grid-area: filters; }
|
||||
.finder__main { grid-area: main; display: grid; gap: var(--space-5); align-content: start; min-inline-size: 0; }
|
||||
.home__lists { grid-area: lists; min-inline-size: 0; }
|
||||
.home__bar { grid-area: bar; min-inline-size: 0; }
|
||||
.home__results { grid-area: results; min-inline-size: 0; }
|
||||
.home__map { grid-area: map; min-inline-size: 0; scroll-margin-block-start: var(--space-4); }
|
||||
.home__notes { grid-area: notes; }
|
||||
.finder__notes { display: grid; gap: var(--space-2); }
|
||||
.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: "filters main" ". notes";
|
||||
grid-template-columns: 18rem minmax(0, 1fr);
|
||||
.home {
|
||||
grid-template-columns: minmax(0, 1fr) 27rem;
|
||||
grid-template-areas: "lists lists" "bar map" "results map" "notes .";
|
||||
}
|
||||
.home__map { position: sticky; inset-block-start: var(--space-4); }
|
||||
.home__map .map { aspect-ratio: auto; block-size: clamp(20rem, calc(100dvh - 17rem), 46rem); }
|
||||
.filters__maplink { display: none; }
|
||||
.home .results-head { padding-block-end: var(--space-2); }
|
||||
}
|
||||
/* Beside the list, the filters stay on screen while the list scrolls. The panel
|
||||
is never taller than the window: when its fields do not fit (a short window,
|
||||
or "More filters" opened) it scrolls on its own, so every filter can be
|
||||
reached from anywhere in the list. Its reset button stays at its foot.
|
||||
The wheel must always move something: over the panel it scrolls the panel
|
||||
while the panel has further to go, and the page otherwise. So no
|
||||
overscroll-behavior here: in Chromium it stops the wheel reaching the page
|
||||
even when the panel has nothing to scroll. */
|
||||
@media (min-width: 64rem) and (pointer: fine) {
|
||||
.home .results-sort .select { min-block-size: 2.25rem; }
|
||||
.home .lists-row .chips a { min-block-size: 2rem; }
|
||||
.home .filters__bar .input, .home .filters__bar .button { min-block-size: 2.5rem; }
|
||||
}
|
||||
/* Beside the map the rows are a little closer, so more of the list is in view. */
|
||||
@media (min-width: 64rem) {
|
||||
.filters {
|
||||
position: sticky; inset-block-start: var(--space-4); align-self: start;
|
||||
max-block-size: calc(100vh - 2 * var(--space-4));
|
||||
max-block-size: calc(100dvh - 2 * var(--space-4));
|
||||
overflow-y: auto; scrollbar-width: thin;
|
||||
}
|
||||
.filters .filters__reset {
|
||||
position: sticky; inset-block-end: 0; z-index: 1;
|
||||
background: var(--surface); border-block-start: 1px solid var(--rule-strong);
|
||||
}
|
||||
.home .entry { padding-block: 0.5rem; }
|
||||
}
|
||||
|
||||
/* Filters: search always shown; the rest folds away on narrow screens */
|
||||
.filters { border: 1px solid var(--ink); background: var(--surface); }
|
||||
.filters .filters__search { padding: var(--space-4); }
|
||||
/* A field placed between the search box and the folded filters (the
|
||||
downloadable-line check) sits outside both padded areas. */
|
||||
.filters > .field:not(.filters__search) { padding: 0 var(--space-4) var(--space-4); }
|
||||
/* The search bar: the search field, a Filters control that opens the panels, Clear (shown only
|
||||
when something is set), and on a narrow screen a link to the map. */
|
||||
.filters__bar { display: flex; align-items: stretch; gap: var(--space-2); }
|
||||
.filters__search { flex: 1 1 auto; min-inline-size: 0; }
|
||||
.filters__bar .button { flex: none; min-block-size: 2.75rem; }
|
||||
.filters__toggle { gap: var(--space-2); }
|
||||
.filters__toggle[aria-expanded="true"] { background: var(--ink); border-color: var(--ink); color: var(--paper); }
|
||||
.filters__toggle .filters__count:not(:empty) { background: var(--paper); color: var(--ink); }
|
||||
.filters__clear[hidden] { display: none; }
|
||||
/* The panels: the existing filter fields, in columns where there is room. With JavaScript they
|
||||
open from the bar; without it the bar and panels are not offered at all (see below). */
|
||||
.filters__panels { margin-block-start: var(--space-2); border: 1px solid var(--ink); background: var(--surface); }
|
||||
html.js .filters__panels:not([data-open]) { display: none; }
|
||||
.filters__panel > summary { display: none; }
|
||||
.filters__more > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1041,12 +1050,12 @@ html:not(.js) .js-only { display: none !important; }
|
||||
letter-spacing: 0.02em;
|
||||
text-transform: none;
|
||||
}
|
||||
.filters__form { display: grid; gap: var(--space-4); padding: var(--space-4); }
|
||||
/* Two columns only while the filters sit above the list at full width; beside
|
||||
the list the panel is narrow and every filter is one column. */
|
||||
@media (min-width: 40rem) and (max-width: 63.99rem) {
|
||||
.filters__form { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.filters__form .field--wide { grid-column: 1 / -1; }
|
||||
/* The fields run in as many columns as the panel has room for. */
|
||||
.filters__first, .filters__form {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(100%, 15rem), 1fr));
|
||||
gap: var(--space-4) var(--space-5);
|
||||
padding: var(--space-4);
|
||||
}
|
||||
|
||||
.field { display: grid; align-content: start; gap: var(--space-2); min-inline-size: 0; margin: 0; padding: 0; border: 0; }
|
||||
@@ -1142,7 +1151,6 @@ html:not(.js) .js-only { display: none !important; }
|
||||
/* 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: "main" "notes"; grid-template-columns: minmax(0, 1fr); }
|
||||
html:not(.js) .list-head__sort { cursor: default; }
|
||||
html:not(.js) .list-head__arrow { display: none; }
|
||||
|
||||
@@ -1426,17 +1434,23 @@ html:not(.js) .list-head__arrow { display: none; }
|
||||
.titleblock--with-plate .titleblock__text > :first-child { grid-column: 2; grid-row: 1; align-self: center; }
|
||||
}
|
||||
|
||||
/* Trail page body: map, then the primary actions (downloads or guides), then the record.
|
||||
On wide screens the actions sit beside the map. The aside is often taller than
|
||||
the viewport, so it scrolls with the page rather than sticking. */
|
||||
/* Trail page body. The first screen holds the map and the key facts: a short lead and the
|
||||
buttons, then the map, in the left column; At a glance (and the downloads under it) in the
|
||||
right one, level with the top of the left. On a narrow screen the order is the buttons, the
|
||||
facts, the map, the elevation profile and the downloads. The aside is often taller than the
|
||||
viewport, so it scrolls with the page rather than sticking. */
|
||||
.detail {
|
||||
display: grid;
|
||||
gap: var(--space-5) var(--space-6);
|
||||
gap: var(--space-4) var(--space-6);
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-areas: "glance" "map" "aside";
|
||||
grid-template-areas: "lead" "glance" "map" "aside";
|
||||
align-items: start;
|
||||
padding-block-start: var(--space-3);
|
||||
}
|
||||
.detail--with-profile { grid-template-areas: "glance" "map" "profile" "aside"; }
|
||||
.detail--with-profile { grid-template-areas: "lead" "glance" "map" "profile" "aside"; }
|
||||
.detail__lead { grid-area: lead; display: grid; gap: var(--space-3); min-inline-size: 0; }
|
||||
.detail__lead:not(:has(*)) { display: none; }
|
||||
.detail__side { display: contents; }
|
||||
.detail__glance { grid-area: glance; min-inline-size: 0; }
|
||||
.detail__map { grid-area: map; min-inline-size: 0; }
|
||||
.detail__profile { grid-area: profile; min-inline-size: 0; }
|
||||
@@ -1447,19 +1461,19 @@ html:not(.js) .list-head__arrow { display: none; }
|
||||
.detail {
|
||||
grid-template-columns: minmax(0, 1fr) 22rem;
|
||||
grid-template-rows: auto 1fr;
|
||||
grid-template-areas: "map glance" "map aside";
|
||||
grid-template-areas: "lead side" "map side";
|
||||
}
|
||||
.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; }
|
||||
.detail--with-profile { grid-template-rows: auto 1fr auto; grid-template-areas: "lead side" "map side" "profile profile"; }
|
||||
.detail__lead:not(:has(*)) { display: block; }
|
||||
.detail__side { display: grid; grid-area: side; gap: var(--space-5); align-content: start; min-inline-size: 0; }
|
||||
.detail__side > * { grid-area: auto; }
|
||||
/* The map is as tall as the window allows, and stays in view while the facts and downloads
|
||||
beside it scroll past. */
|
||||
.detail__map { align-self: start; position: sticky; inset-block-start: var(--space-4); }
|
||||
.detail__map .map { aspect-ratio: auto; block-size: clamp(30rem, calc(100dvh - 15rem), 52rem); }
|
||||
/* With no track there is no map: the notice keeps its own height. */
|
||||
.detail--no-map .detail__map { position: static; }
|
||||
.detail--no-map .detail__map .map { block-size: auto; min-block-size: 22rem; }
|
||||
}
|
||||
|
||||
.block + .block { margin-block-start: var(--space-7); }
|
||||
@@ -1736,6 +1750,55 @@ td .linklist a { font-weight: 400; }
|
||||
.prose .table-wrap { max-inline-size: 100%; }
|
||||
.prose .table-wrap table:has(th:nth-child(4)) { min-inline-size: 30rem; }
|
||||
|
||||
/* A table of figures with one trail in each column (the Triple Crown): the columns are equal and
|
||||
the label column narrow, whatever the cells hold; a long value wraps inside its cell. */
|
||||
.table-wrap table[data-stack="columns"] { table-layout: fixed; min-inline-size: 0; }
|
||||
.table-wrap table[data-stack="columns"] th:first-child { inline-size: 9rem; }
|
||||
.table-wrap table[data-stack="columns"] th,
|
||||
.table-wrap table[data-stack="columns"] td { padding: var(--space-3) var(--space-4); overflow-wrap: anywhere; hyphens: auto; }
|
||||
.table-wrap table[data-stack="columns"] tbody th { background: var(--sunken); font-weight: 600; }
|
||||
|
||||
/* Between a phone and a laptop a table with many columns gives up some of its padding. */
|
||||
@media (min-width: 40.01rem) and (max-width: 63.99rem) {
|
||||
.table-wrap table[data-stack="rows"] th, .table-wrap table[data-stack="rows"] td { padding-inline: var(--space-2); }
|
||||
}
|
||||
|
||||
/* On a phone a table is not a grid to scroll. A table with many columns is one block per row (its
|
||||
first cell is the block's title and every other cell is a label and its value, from data-label);
|
||||
a table of trails in columns is one block per trail, headed by the trail's name. One set of
|
||||
markup: the cells carry their labels (olt/pagekit.py). */
|
||||
@media (max-width: 40rem) {
|
||||
.table-wrap:has(table[data-stack]) { overflow: visible; border: 0; background: none; }
|
||||
.table-wrap table[data-stack] { min-inline-size: 0 !important; table-layout: auto; }
|
||||
.table-wrap table[data-stack="rows"] thead,
|
||||
.table-wrap table[data-stack="columns"] thead th:first-child,
|
||||
.table-wrap table[data-stack="columns"] tbody th { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; padding: 0; border: 0; }
|
||||
.table-wrap table[data-stack="rows"],
|
||||
.table-wrap table[data-stack="rows"] tbody,
|
||||
.table-wrap table[data-stack="rows"] tr { display: block; }
|
||||
.table-wrap table[data-stack="rows"] tr { margin-block-end: var(--space-3); background: var(--surface); border: 1px solid var(--rule-strong); }
|
||||
.table-wrap table[data-stack="rows"] tbody tr:last-child td { border-block-end: 1px dotted var(--rule-strong); }
|
||||
.table-wrap table[data-stack="rows"] tr > :first-child { display: block; padding: var(--space-2) var(--space-3); background: var(--sunken); font-weight: 600; border-block-end: 1px solid var(--rule-strong); }
|
||||
.table-wrap table[data-stack="rows"] td:first-child::before { content: none; }
|
||||
.table-wrap table[data-stack] td { display: grid; grid-template-columns: minmax(5.5rem, 7.5rem) minmax(0, 1fr); gap: var(--space-3); align-items: baseline; text-align: start; border-block-end: 1px dotted var(--rule-strong); }
|
||||
.table-wrap table[data-stack] td:last-child { border-block-end: 0; }
|
||||
.table-wrap table[data-stack] td::before { content: attr(data-label); color: var(--ink-2); font: 600 var(--step--2)/1.4 var(--font-sans); letter-spacing: 0.06em; text-transform: uppercase; }
|
||||
.table-wrap table[data-stack="rows"] td.num { text-align: start; }
|
||||
/* Trails in columns: the header cells and the cells of one column are the blocks, in order. */
|
||||
.table-wrap table[data-stack="columns"] { display: grid; border: 1px solid var(--rule-strong); background: var(--surface); }
|
||||
.table-wrap table[data-stack="columns"] thead,
|
||||
.table-wrap table[data-stack="columns"] tbody,
|
||||
.table-wrap table[data-stack="columns"] tr { display: contents; }
|
||||
.table-wrap table[data-stack="columns"] thead th:not(:first-child) { display: block; padding: var(--space-3); background: var(--ink); color: var(--paper); font: 600 var(--step-0)/1.3 var(--font-sans); letter-spacing: 0; border: 0; }
|
||||
.table-wrap table[data-stack="columns"] thead th:nth-child(2), .table-wrap table[data-stack="columns"] td:nth-of-type(1) { order: 1; }
|
||||
.table-wrap table[data-stack="columns"] thead th:nth-child(3), .table-wrap table[data-stack="columns"] td:nth-of-type(2) { order: 2; }
|
||||
.table-wrap table[data-stack="columns"] thead th:nth-child(4), .table-wrap table[data-stack="columns"] td:nth-of-type(3) { order: 3; }
|
||||
.table-wrap table[data-stack="columns"] thead th:nth-child(5), .table-wrap table[data-stack="columns"] td:nth-of-type(4) { order: 4; }
|
||||
.table-wrap table[data-stack="columns"] thead th:nth-child(6), .table-wrap table[data-stack="columns"] td:nth-of-type(5) { order: 5; }
|
||||
.table-wrap table[data-stack="columns"] thead th:nth-child(7), .table-wrap table[data-stack="columns"] td:nth-of-type(6) { order: 6; }
|
||||
.table-wrap table[data-stack="columns"] thead th:nth-child(n+3) { margin-block-start: var(--space-4); }
|
||||
}
|
||||
|
||||
.region-nav { margin-block-start: var(--space-6); font: 400 var(--step--1)/1.5 var(--font-sans); color: var(--ink-2); }
|
||||
.logo-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 19rem), 1fr)); gap: var(--space-4); padding: 0; list-style: none; }
|
||||
.logo-card { display: grid; gap: var(--space-3); padding: var(--space-4); background: var(--surface); border: 1px solid var(--rule-strong); }
|
||||
@@ -1813,12 +1876,35 @@ td .linklist a { font-weight: 400; }
|
||||
|
||||
/* 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; }
|
||||
/* The generated "In brief" paragraph and the date of the last check, under the lede. */
|
||||
.trail-brief { max-inline-size: 46rem; margin-block-start: var(--space-3); line-height: 1.55; text-wrap: pretty; }
|
||||
.trail-checked { margin-block-start: var(--space-2); }
|
||||
.trail-actions { margin-block-start: var(--space-4); }
|
||||
.page-head .titleblock { margin-block-end: var(--space-4); }
|
||||
/* The top of every page is compact: breadcrumb, then the name, so that what the page is for is
|
||||
on the first screen (the map and the facts of a trail, the first trails of a list). */
|
||||
.page-head { padding-block: var(--space-3) 0; }
|
||||
.page-head .titleblock { margin-block: var(--space-2) 0; gap: var(--space-2) var(--space-4); }
|
||||
.page-head .titleblock h1 { font-size: var(--step-3); line-height: 1.1; }
|
||||
.page-head .titleblock--with-plate { grid-template-columns: 4.5rem minmax(0, 1fr); }
|
||||
.page-head .titleblock .plate { padding: 0.35rem; }
|
||||
.page-head .titleblock__text { gap: var(--space-1); }
|
||||
.page-head .titleblock__sub { font-size: var(--step-0); }
|
||||
@media (min-width: 48rem) {
|
||||
.page-head .titleblock--with-plate { grid-template-columns: 6rem minmax(0, 1fr); }
|
||||
}
|
||||
/* The lead above the map: the first sentence of the summary, when it is short. The summary in
|
||||
full is under the map. */
|
||||
.trail-lede { max-inline-size: 46rem; font-size: var(--step-0); line-height: 1.45; text-wrap: pretty; }
|
||||
.trail-actions { margin-block-start: 0; }
|
||||
/* On a phone the buttons come first. */
|
||||
@media (max-width: 47.99rem) {
|
||||
.detail__lead { display: flex; flex-direction: column; }
|
||||
.detail__lead .trail-actions { order: -1; }
|
||||
}
|
||||
/* Under the map: the summary in full, the generated "In brief" paragraph, the date of the last
|
||||
check, and the other pages about the trail. */
|
||||
.trail-text { max-inline-size: 46rem; margin-block-end: var(--space-6); }
|
||||
.trail-text > h2 { margin-block-end: var(--space-3); font-size: var(--step-2); }
|
||||
.trail-summary { font-size: var(--step-1); line-height: 1.5; text-wrap: pretty; }
|
||||
.trail-brief { margin-block-start: var(--space-3); line-height: 1.55; text-wrap: pretty; }
|
||||
.trail-checked { margin-block-start: var(--space-3); }
|
||||
.trail-more .morelinks { max-inline-size: 46rem; margin-block-end: var(--space-6); }
|
||||
|
||||
/* At a glance: the hiker's facts, a legend box like the panels */
|
||||
.glance { border: 1px solid var(--ink); background: var(--surface); }
|
||||
@@ -1858,6 +1944,19 @@ td .linklist a { font-weight: 400; }
|
||||
font: 400 var(--step--1)/1.45 var(--font-sans);
|
||||
}
|
||||
.glance > .note { padding: 0 var(--space-4) var(--space-4); }
|
||||
/* Below the two-column page the panel shows its first facts, so the map is on the first screen;
|
||||
a button opens the rest. Without JavaScript every fact shows and the button is not offered. */
|
||||
.glance__toggle { display: none; }
|
||||
@media (max-width: 63.99rem) {
|
||||
html.js .glance:not([data-all]) .glance__facts > div:nth-child(n+5),
|
||||
html.js .glance:not([data-all]) > .note { display: none; }
|
||||
html.js .glance__toggle {
|
||||
display: block; inline-size: 100%; min-block-size: 2.75rem; padding: var(--space-2) var(--space-4);
|
||||
border: 0; border-block-start: 1px solid var(--rule-strong); background: var(--sunken); color: var(--link);
|
||||
font: 600 var(--step--1)/1.3 var(--font-sans); text-align: start; cursor: pointer;
|
||||
}
|
||||
.glance__toggle:hover { background: var(--paper); }
|
||||
}
|
||||
|
||||
/* Elevation profile: a legend box like the glance, the line drawn as SVG */
|
||||
.elev { border: 1px solid var(--ink); background: var(--surface); }
|
||||
@@ -1990,7 +2089,6 @@ td .linklist a { font-weight: 400; }
|
||||
|
||||
.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); }
|
||||
@@ -1999,18 +2097,25 @@ td .linklist a { font-weight: 400; }
|
||||
|
||||
/* 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); }
|
||||
.hero--short { padding-block: var(--space-3) var(--space-2); }
|
||||
.hero--short .hero__inner { gap: var(--space-1); }
|
||||
/* The home page's lists: a short row. The label leads it, and the pills fit one row or two on a
|
||||
wide screen; on a phone they are one row that scrolls sideways within itself. */
|
||||
.lists-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-4); }
|
||||
.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; }
|
||||
.lists-row .chips { flex: 1 1 0; min-inline-size: 0; }
|
||||
@media (min-width: 40rem) and (pointer: fine) { .lists-row .chips a { min-block-size: 2.25rem; } }
|
||||
@media (max-width: 39.99rem) {
|
||||
.lists-row { display: grid; gap: var(--space-1); }
|
||||
.lists-row .chips {
|
||||
flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; overscroll-behavior-x: contain;
|
||||
margin-inline: calc(-1 * var(--gutter)); padding: 3px var(--gutter);
|
||||
}
|
||||
/* The row scrolls by touch; a scrollbar under it reads as a stray white band */
|
||||
.lists-row .chips::-webkit-scrollbar { display: none; }
|
||||
.lists-row .chips li { flex: none; }
|
||||
}
|
||||
.section--finder { padding-block-start: var(--space-4); }
|
||||
.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); }
|
||||
@@ -2053,6 +2158,21 @@ a.tag:hover { background: var(--sunken); }
|
||||
.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); }
|
||||
.section.place { padding-block-start: var(--space-4); }
|
||||
/* A place, list or routes page: the list, then the map, then the page's own text; on a wide
|
||||
screen the list beside the text and the map, which stays in view as the list scrolls. */
|
||||
.place-grid {
|
||||
display: grid; align-items: start; gap: var(--space-5) var(--space-6);
|
||||
grid-template-columns: minmax(0, 1fr); grid-template-areas: "list" "map" "text";
|
||||
}
|
||||
.place-grid__text { grid-area: text; min-inline-size: 0; }
|
||||
.place-grid__list { grid-area: list; min-inline-size: 0; }
|
||||
.place-grid__map { grid-area: map; min-inline-size: 0; }
|
||||
@media (min-width: 64rem) {
|
||||
.place-grid { grid-template-columns: minmax(0, 1fr) 27rem; grid-template-rows: auto minmax(0, 1fr); grid-template-areas: "list text" "list map"; gap: var(--space-4) var(--space-6); }
|
||||
.place-grid__map { position: sticky; inset-block-start: var(--space-4); }
|
||||
.place-grid__map .map { aspect-ratio: auto; block-size: clamp(18rem, calc(100dvh - 17rem), 40rem); }
|
||||
}
|
||||
|
||||
/* 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; }
|
||||
@@ -2060,24 +2180,7 @@ a.tag:hover { background: var(--sunken); }
|
||||
.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
|
||||
|
||||
|
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 20 KiB |
@@ -41,6 +41,22 @@ def line_short(rec):
|
||||
return line_differs(rec) and rec["verification"]["difference_percent"] < 0
|
||||
|
||||
|
||||
def built_text(rec):
|
||||
""""290 mi built" for an unfinished trail whose holder states the built length; else "". Markup."""
|
||||
if not rec.get("built_km"):
|
||||
return Markup("")
|
||||
return Markup(f"{words.length(rec['built_km'], 'inline')} built")
|
||||
|
||||
|
||||
def system_text(rec):
|
||||
""""Whole system: 1,584 mi, counting all designated trail ..." where the holder publishes a
|
||||
larger figure; else "". Markup. The note says what the figure counts (system_note)."""
|
||||
if not rec.get("system_km"):
|
||||
return Markup("")
|
||||
return Markup(f"Whole system: {words.length(rec['system_km'], 'inline')}, "
|
||||
f"counting {esc(str(rec.get('system_note', '')).strip().rstrip('.'))}")
|
||||
|
||||
|
||||
def partial_short_text(rec):
|
||||
"""The short form for lists: "Track measures 1.2 mi (2.0 km) of 684 mi (1,100 km) published",
|
||||
in the reader's unit order (words.length). Markup."""
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
glossary.toml [[term]] the Glossary page (olt/reference.py)
|
||||
collections.toml [[collection]] named sets of trails set side by side (olt/standing.py)
|
||||
[[list]] which lists the home page shows, and in what order (olt/home.py)
|
||||
authors.toml [[author]] route authors credited in more than one form (olt/authors.py)
|
||||
|
||||
Each is checked by tools/validate.py and described in docs/schema.md. Like left-out.toml, a file
|
||||
@@ -34,3 +35,8 @@ def collections(repo_root):
|
||||
|
||||
def authors(repo_root):
|
||||
return load(repo_root, "authors.toml", "author")
|
||||
|
||||
|
||||
def lists(repo_root):
|
||||
"""The [[list]] entries of collections.toml: a list's key, and `home`, its place in the home page's row."""
|
||||
return load(repo_root, "collections.toml", "list")
|
||||
@@ -373,8 +373,9 @@ site calls them trails.</p>
|
||||
<p>A trail is listed when it is a named, continuous walk, or a named loop, of at least 50 miles (80 km)
|
||||
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 37 and 50 miles (60 and 80 km).</p>
|
||||
{routes} of the {n} trails are routes. The length is the end-to-end length of the trail’s canonical path, and the
|
||||
trail must be walkable from one end to the other today. A National Scenic Trail is listed unless it cannot be walked
|
||||
through, and so are a few well-known multi-day trails between 37 and 50 miles (60 and 80 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>
|
||||
<p>Trails that were looked at and left out are kept in the open too, with the reason for each one:
|
||||
|
||||
@@ -7,7 +7,7 @@ attributes in olt/facets.py, under the same names the trail pages use.
|
||||
import collections
|
||||
import math
|
||||
|
||||
from . import browse, common, facets, hike, words
|
||||
from . import browse, common, datafiles, facets, hike, sketch, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
# Length range choices for the filters, round in the unit they are written in.
|
||||
@@ -68,17 +68,22 @@ def counts(records):
|
||||
return c
|
||||
|
||||
|
||||
def overview_bbox(records):
|
||||
"""data-bbox attribute: the extent of every track and sketch, so the map opens on it before the data loads."""
|
||||
def overview_box(records):
|
||||
"""[west, south, east, north] of every track and sketch of these trails, or None."""
|
||||
boxes = [r["derived"]["bbox"] for r in records if r["derived"].get("bbox")]
|
||||
for r in records:
|
||||
box = hike.sketch_bbox(hike.sketch_points(r))
|
||||
if box:
|
||||
boxes.append(box)
|
||||
if not boxes:
|
||||
return ""
|
||||
box = [min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)]
|
||||
return f' data-bbox="{",".join(f"{v:.4f}" for v in box)}"'
|
||||
return None
|
||||
return [min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)]
|
||||
|
||||
|
||||
def overview_bbox(records):
|
||||
"""data-bbox attribute: the extent of every track and sketch, so the map opens on it before the data loads."""
|
||||
box = overview_box(records)
|
||||
return f' data-bbox="{",".join(f"{v:.4f}" for v in box)}"' if box else ""
|
||||
|
||||
|
||||
sort_name = facets.sort_name
|
||||
@@ -304,24 +309,28 @@ def finder_form(records, c=None, steps=None):
|
||||
{_checks("gpx", facets.GPX_FILTER.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 author of a route" autocomplete="off" spellcheck="false">
|
||||
<div class="filters__bar">
|
||||
<div class="filters__search field">
|
||||
<label class="vh" for="q">Search</label>
|
||||
<input class="input" id="q" name="q" type="search" placeholder="Search by name, abbreviation or author" autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<button class="button filters__toggle js-only" type="button" aria-expanded="false" aria-controls="filters-panels">Filters <span class="filters__count"></span></button>
|
||||
<button class="button button--quiet filters__clear" type="reset" hidden>Clear</button>
|
||||
<a class="button button--quiet filters__maplink" href="#map">Map</a>
|
||||
</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 class="filters__panels" id="filters-panels">
|
||||
<details class="filters__panel" open>
|
||||
<summary>Filters</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>
|
||||
</form>"""
|
||||
|
||||
@@ -559,11 +568,19 @@ def overview_map(recs, label, *, wide=False, scope="", saved=False):
|
||||
ids_attr += f' data-drawable="{esc(" ".join(ids))}"'
|
||||
sentences.append("Each trail’s page names its source, credit and licence. "
|
||||
"Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.")
|
||||
return Markup(f"""<figure class="mapfig{" mapfig--wide" if wide else ""}" data-map="overview" data-src="/data/overview.geojson"{ids_attr}{overview_bbox(recs)}>
|
||||
# The tracks are drawn into the page, on the ground the live map opens on (olt/sketch.py). The
|
||||
# Saved page has none: which trails it draws is the visitor's own, so app.js draws them.
|
||||
frame_attr, drawing = "", ""
|
||||
box = overview_box(recs)
|
||||
if box and not saved:
|
||||
fr = sketch.frame(box)
|
||||
frame_attr = f' data-frame="{",".join(f"{v:g}" for v in fr)}"'
|
||||
drawing = sketch.svg(sketch.overview_features(ids), fr, ident=True)
|
||||
return Markup(f"""<figure class="mapfig{" mapfig--wide" if wide else ""}" data-map="overview" data-src="/data/overview.geojson"{ids_attr}{overview_bbox(recs)}{frame_attr}>
|
||||
<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__fallback">{drawing}</div>
|
||||
<div class="map__canvas"></div>
|
||||
<p class="map__status" role="status">The map needs JavaScript. The list has every trail.</p>
|
||||
</div>
|
||||
@@ -578,18 +595,32 @@ def overview_map(recs, label, *, wide=False, scope="", saved=False):
|
||||
</figure>""")
|
||||
|
||||
|
||||
def place_grid(text_html, listing, map_html):
|
||||
"""The body of a place, list or routes page: the list beside its map on a wide screen, with the
|
||||
page's own text above the map there, so that the first trails are on the first screen. On a
|
||||
narrow screen the list comes first, then the map, then the text (style.css .place-grid)."""
|
||||
return f"""<div class="place-grid">
|
||||
<div class="place-grid__text">{text_html}</div>
|
||||
<div class="place-grid__list">{listing}</div>
|
||||
<div class="place-grid__map">{map_html}</div>
|
||||
</div>"""
|
||||
|
||||
|
||||
def has_overview_map(recs, scope=""):
|
||||
"""True when overview_map would draw a map of these trails (needs the map library)."""
|
||||
n = len(drawable_ids(recs))
|
||||
return n > 0 and (scope == "all" or n >= MAP_MIN)
|
||||
|
||||
|
||||
def lists_row(records):
|
||||
"""The ready-made lists, as a row of links with their counts. The terrain lists are
|
||||
on /lists/; here the Terrain filter does the same work."""
|
||||
def lists_row(records, picks=()):
|
||||
"""The row of lists on the home page: the lists the data file marks for it (picks, from
|
||||
datafiles.home_lists: key and position), in that order, each with its count, then "All lists".
|
||||
A marked list that is not shown today (too few trails, or nearly all of them) is left out."""
|
||||
have = {lst.key: (lst, recs) for lst, recs in browse.shown(records)}
|
||||
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-"))
|
||||
f'<li><a href="{esc(browse.path(have[key][0]))}">{esc(have[key][0].title)} '
|
||||
f'<span class="chips__n">{len(have[key][1])}</span></a></li>'
|
||||
for key in picks if key in have)
|
||||
if not items:
|
||||
return ""
|
||||
return f"""<nav class="lists-row" aria-labelledby="lists-title">
|
||||
@@ -598,6 +629,12 @@ def lists_row(records):
|
||||
</nav>"""
|
||||
|
||||
|
||||
def home_picks(entries):
|
||||
"""The keys of the lists marked for the home page, in the order of their `home` positions."""
|
||||
marked = [e for e in entries if isinstance(e.get("home"), int)]
|
||||
return [e["key"] for e in sorted(marked, key=lambda e: e["home"])]
|
||||
|
||||
|
||||
def description(records):
|
||||
"""The home page's meta description: how many, what each has, and how many have a GPX."""
|
||||
n_gpx = sum(1 for r in records if facets.gpx_here(r))
|
||||
@@ -606,8 +643,8 @@ def description(records):
|
||||
return common.cut_at_word(text, common.DESCRIPTION_LIMIT)
|
||||
|
||||
|
||||
def render(records, site):
|
||||
"""The home page body (HTML)."""
|
||||
def render(records, site, repo_root=""):
|
||||
"""The home page body (HTML). repo_root: where collections.toml names the lists the page shows."""
|
||||
c = counts(records)
|
||||
recs = sorted(records, key=sort_name)
|
||||
total = c["total"]
|
||||
@@ -618,32 +655,21 @@ def render(records, site):
|
||||
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>.</p>')
|
||||
picks = home_picks(datafiles.lists(repo_root))
|
||||
return f"""<section class="hero hero--short hero--home" aria-labelledby="hero-title">
|
||||
<div class="container hero__inner">
|
||||
<h1 id="hero-title" class="lockup"><img class="lockup__mark" src="/assets/favicon.svg" alt="" width="96" height="96">{esc(site.name)}<span class="vh">: long-distance hiking trails of the United States and Canada</span></h1>
|
||||
<p class="hero__tagline">{esc(site.tagline.rstrip("."))}.</p>
|
||||
<ul class="hero__tags">
|
||||
<li><a href="#finder">Filters</a></li>
|
||||
<li><a href="/lists/with-gpx/">GPX</a></li>
|
||||
<li><a href="/sources/">A source for every fact</a></li>
|
||||
<li><a href="/data/">Open data</a></li>
|
||||
</ul>
|
||||
<h1 id="hero-title">{esc(site.tagline.rstrip("."))}</h1>
|
||||
<p class="hero__lede">{lede}</p>
|
||||
{lists_row(records)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section section--finder" id="finder" aria-labelledby="finder-title">
|
||||
<div class="container finder__grid">
|
||||
<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’s own maps before you go.</p>
|
||||
{contribute}
|
||||
</div>
|
||||
<div class="container home" id="finder">
|
||||
<div class="home__lists">{lists_row(records, picks)}</div>
|
||||
<h2 class="vh" id="finder-title">Every trail</h2>
|
||||
<div class="home__bar">{finder_form(records, c, length_steps(records))}</div>
|
||||
<div class="home__results">{results(recs, finder=True)}</div>
|
||||
<div class="home__map" id="map">{overview_map(records, "Map of the trails the filters leave", wide=True, scope="all")}</div>
|
||||
<div class="home__notes finder__notes">
|
||||
<p class="finder__foot">Not for navigation: tracks vary in quality and some trails are unfinished. Check each trail’s own maps before you go.</p>
|
||||
{contribute}
|
||||
</div>
|
||||
</section>"""
|
||||
</div>"""
|
||||
@@ -24,14 +24,19 @@ from .markup import Markup, attrs, esc, json_block
|
||||
NAV = (
|
||||
("Trails", "/"),
|
||||
("Places", "/regions/"),
|
||||
("Lists", "/lists/"),
|
||||
("About", "/about/"),
|
||||
)
|
||||
# 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/": "/",
|
||||
# Pages with no header item of their own, and the item they sit under. A trail's page is part of
|
||||
# Trails; the dataset pages are part of About and are linked from the About hub and the footer.
|
||||
NAV_PARENT = {"/trails/": "/",
|
||||
"/sources/": "/about/", "/logos/": "/about/", "/data/": "/about/",
|
||||
"/left-out/": "/about/"}
|
||||
"/left-out/": "/about/", "/method/": "/about/", "/glossary/": "/about/"}
|
||||
# Under Lists: the lists (Routes among them), the tables and rankings, the authors and the views of
|
||||
# what is new. A table that collections.toml names has an address of its own; olt/pages.py adds it
|
||||
# to UNDER_LISTS as it writes the page.
|
||||
LISTS_PREFIXES = ("/lists/", "/routes/", "/numbers/", "/authors/", "/recent/", "/connected/")
|
||||
UNDER_LISTS = set()
|
||||
|
||||
FEED_PATH = "/feed.xml" # the Atom feed of the changelog (olt/feed.py)
|
||||
|
||||
@@ -45,6 +50,7 @@ FONT_PRELOADS = (
|
||||
"/assets/fonts/ibm-plex-sans-condensed-500-latin.woff2",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-600-latin.woff2",
|
||||
)
|
||||
CONTOURS = "/assets/contours.svg"
|
||||
MAPLIBRE_CSS = "/assets/vendor/maplibre-gl/maplibre-gl.css"
|
||||
MAPLIBRE_JS = "/assets/vendor/maplibre-gl/maplibre-gl.js"
|
||||
# The outdoor map of the trail pages: its style, named on each trail map figure
|
||||
@@ -56,11 +62,11 @@ CONTOUR_JS = "/assets/vendor/maplibre-contour/maplibre-contour.js"
|
||||
|
||||
def _current(path, href):
|
||||
"""True when the nav item href is the section the page at path belongs to."""
|
||||
if href == "/" and path == "/":
|
||||
return True
|
||||
if href == "/lists/":
|
||||
return path.startswith(LISTS_PREFIXES) or path in UNDER_LISTS
|
||||
if any(path.startswith(p) and parent == href for p, parent in NAV_PARENT.items()):
|
||||
return True
|
||||
return href != "/" and path.startswith(href)
|
||||
return path == "/" if href == "/" else path.startswith(href)
|
||||
|
||||
|
||||
SAVED_PATH = "/saved/"
|
||||
@@ -207,7 +213,7 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
|
||||
description meta description (155 characters); defaults to the site tagline. The share
|
||||
descriptions (og:description, twitter:description) are cut from it to 125.
|
||||
maps True on a page with a .mapfig[data-map]: app.js is given the addresses of
|
||||
MapLibre, and loads it when the map scrolls into view or is touched.
|
||||
MapLibre, and loads it a moment after the page has loaded.
|
||||
outdoor True as well on a page whose map is an outdoor map (a trail
|
||||
page): app.js loads the contour add-on with MapLibre.
|
||||
scripts extra same-origin script URLs, loaded with defer after app.js.
|
||||
@@ -275,14 +281,17 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
|
||||
head += [f'<link rel="alternate" type="{esc(kind)}" href="{esc(href)}"{attrs(title=name)}>'
|
||||
for href, kind, name in alternates]
|
||||
head += [f'<link rel="preload" href="{fingerprint.url(f)}" as="font" type="font/woff2" crossorigin>' for f in FONT_PRELOADS]
|
||||
# The contour picture behind the page head: found by the stylesheet only, so it would arrive after
|
||||
# the first paint and, on a compact head, be the last thing painted (the page's largest paint).
|
||||
head.append(f'<link rel="preload" href="{fingerprint.url(CONTOURS)}" as="image" type="image/svg+xml">')
|
||||
head += [
|
||||
f'<link rel="stylesheet" href="{fingerprint.url("/assets/style.css")}">',
|
||||
# Sets the theme and unit preference before first paint (no inline scripts allowed).
|
||||
f'<script src="{fingerprint.url("/assets/prefs.js")}"></script>',
|
||||
]
|
||||
# The page's one script. A page with a map does not load MapLibre (200 KB of script, 65 KB
|
||||
# of style) with the page: app.js loads these three files itself, when the map scrolls
|
||||
# into view or is touched, from the addresses it is given here.
|
||||
# of style) with the page: app.js loads these three files itself, a moment after the page has
|
||||
# loaded and never on a scroll or a touch, from the addresses it is given here.
|
||||
libs = {}
|
||||
if maps:
|
||||
libs = {"data-maplibre-css": MAPLIBRE_CSS, "data-maplibre-js": MAPLIBRE_JS}
|
||||
|
||||
@@ -117,17 +117,17 @@ def left_out_page(entries, site, repo_root):
|
||||
if e.get("source_url"):
|
||||
source = (f'<a href="{esc(e["source_url"])}">Source page</a>')
|
||||
rows += (
|
||||
f"<tr><td>{esc(e.get('name', ''))}{mark}</td>"
|
||||
f"<td>{esc(_where(e))}</td>"
|
||||
f"<td>{_length(e)}</td>"
|
||||
f"<td>{why}</td>"
|
||||
f'<td><time datetime="{esc(e.get("decided", ""))}">'
|
||||
f'<tr><td data-label="Trail">{esc(e.get("name", ""))}{mark}</td>'
|
||||
f'<td data-label="Where">{esc(_where(e))}</td>'
|
||||
f'<td data-label="Length">{_length(e)}</td>'
|
||||
f'<td data-label="Why it is left out">{why}</td>'
|
||||
f'<td data-label="Decided"><time datetime="{esc(e.get("decided", ""))}">'
|
||||
f"{esc(e.get('decided', ''))}</time></td>"
|
||||
f"<td>{source}</td></tr>")
|
||||
f'<td data-label="Source">{source}</td></tr>')
|
||||
groups += f"""<section aria-labelledby="left-out-{esc(reason)}">
|
||||
<div class="section-head"><h2 id="left-out-{esc(reason)}">{esc(heading)}</h2>
|
||||
<p>{esc(meaning)}</p></div>
|
||||
<div class="table-wrap"><table>
|
||||
<div class="table-wrap"><table data-stack="rows">
|
||||
<thead><tr><th scope="col">Trail</th><th scope="col">Where</th><th scope="col">Length</th><th scope="col">Why it is left out</th><th scope="col">Decided</th><th scope="col">Source</th></tr></thead>
|
||||
<tbody>{rows}</tbody></table></div>
|
||||
</section>"""
|
||||
|
||||
@@ -16,23 +16,36 @@ def head(h1, lede_html, crumbs, *, kicker=""):
|
||||
</div></div>"""
|
||||
|
||||
|
||||
def table(headers, rows, *, caption="", numeric=(), row_heads=False):
|
||||
# A table with at least this many columns is set as one block per row on a phone (style.css).
|
||||
STACK_COLUMNS = 4
|
||||
|
||||
|
||||
def table(headers, rows, *, caption="", numeric=(), row_heads=False, compare=False):
|
||||
"""A table in the site's table wrapper. headers: column titles; rows: lists of HTML cells
|
||||
(Markup, or text that is escaped); numeric: column numbers set at the end of the cell;
|
||||
row_heads: the first cell of each row is a row heading."""
|
||||
def cell(i, value, head=False):
|
||||
row_heads: the first cell of each row is a row heading.
|
||||
|
||||
Every cell carries its label (data-label: its column's title, or in a compare table its row's
|
||||
heading) so that a phone can set the same markup as blocks, with no sideways scrolling
|
||||
(style.css): one block per row where the table has STACK_COLUMNS columns or more, and
|
||||
compare: a table of figures down the side and one trail in each column, with a fixed layout
|
||||
of equal columns, and on a phone one block per trail, headed by the trail's name."""
|
||||
def cell(i, value, label, head=False):
|
||||
text = value if isinstance(value, Markup) else esc(value)
|
||||
cls = ' class="num"' if i in numeric else ""
|
||||
if head:
|
||||
return f'<th scope="row"{cls}>{text}</th>'
|
||||
return f"<td{cls}>{text}</td>"
|
||||
return f'<td{cls} data-label="{esc(label)}">{text}</td>'
|
||||
cap = f'<caption class="vh">{esc(caption)}</caption>' if caption else ""
|
||||
num = ' class="num"'
|
||||
head = "".join(f'<th scope="col"{num if i in numeric else ""}>{esc(h)}</th>' for i, h in enumerate(headers))
|
||||
body = "".join(
|
||||
"<tr>" + "".join(cell(i, v, head=row_heads and i == 0) for i, v in enumerate(row)) + "</tr>"
|
||||
"<tr>" + "".join(cell(i, v, row[0] if compare else headers[i], head=row_heads and i == 0)
|
||||
for i, v in enumerate(row)) + "</tr>"
|
||||
for row in rows)
|
||||
return Markup(f'<div class="table-wrap"><table>{cap}<thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>')
|
||||
mode = "columns" if compare else "rows" if len(headers) >= STACK_COLUMNS else ""
|
||||
stack = f' data-stack="{mode}"' if mode else ""
|
||||
return Markup(f'<div class="table-wrap"><table{stack}>{cap}<thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>')
|
||||
|
||||
|
||||
def trail_link(rec):
|
||||
|
||||
@@ -31,7 +31,7 @@ import os
|
||||
import shutil
|
||||
|
||||
from .markup import esc
|
||||
from . import authors, browse, cards, datafiles, docs, facets, feed, home, layout, leftout, pagekit, placefacets, reference, regions, saved, seo, site as site_settings, standing, thumbs, trail, views
|
||||
from . import authors, browse, cards, datafiles, docs, facets, feed, home, layout, leftout, pagekit, placefacets, reference, regions, saved, seo, site as site_settings, sketch, standing, thumbs, trail, views
|
||||
|
||||
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ASSETS_DIR = os.path.join(WEB_DIR, "assets")
|
||||
@@ -86,6 +86,8 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
"""Write every HTML page for the given records. Returns the number of pages written."""
|
||||
site = site or site_settings.load()
|
||||
copy_assets(out_dir)
|
||||
sketch.use(out_dir) # the maps' static drawings are read from the track files written here
|
||||
layout.UNDER_LISTS.clear()
|
||||
pages = 0
|
||||
dates = {} # page path -> its own date (YYYY-MM-DD), for the sitemap
|
||||
everything = seo.newest(records)
|
||||
@@ -105,7 +107,7 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
image=card, image_alt=card_alt))
|
||||
dates[path] = seo.modified(rec)
|
||||
pages += 1
|
||||
body = home.render(records, site)
|
||||
body = home.render(records, site, repo_root)
|
||||
layout.write_page(out_dir, "/", layout.layout("", body, path="/", maps=True, site=site,
|
||||
description=home.description(records),
|
||||
jsonld=seo.home_jsonld(site)))
|
||||
@@ -161,6 +163,7 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
recs = built[3] if len(built) > 3 and isinstance(built[3], list) else None
|
||||
pending.append((path, t, d, b, {"recs": recs}))
|
||||
view_paths.append(path)
|
||||
layout.UNDER_LISTS.add(path) # its header item is Lists
|
||||
labels[path] = link_label
|
||||
if group:
|
||||
extras.append((group, link_label, blurb, path, len(recs) if recs else 0))
|
||||
|
||||
@@ -105,9 +105,8 @@ def page(p, records, site, all_pages):
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
<div class="prose place-summary">{summary.facts(recs, records)}</div>
|
||||
{home.overview_map(recs, f"Map of the trails in {name}: {lst.title}")}
|
||||
{home.results(recs, default_sort=lst.sort, top=2)}
|
||||
{home.place_grid(f'<div class="prose place-summary">{summary.facts(recs, records)}</div>', home.results(recs, default_sort=lst.sort, top=2),
|
||||
home.overview_map(recs, f"Map of the trails in {name}: {lst.title}"))}
|
||||
<nav class="region-nav" aria-label="Lists"><a href="{esc(browse.path(lst))}">{esc(lst.title)} everywhere</a> · <a href="/lists/">All lists</a></nav>
|
||||
{nav}
|
||||
</div>"""
|
||||
|
||||
@@ -108,6 +108,8 @@ def method_page(records, site, repo_root):
|
||||
gaps = sum(1 for r, _ in ver if r.get("source", {}).get("length_gap_note"))
|
||||
mid = statistics.median(abs(d) for _, d in ver) if ver else 0
|
||||
no_track = sum(1 for r in records if not common.has_line(r))
|
||||
n_system = sum(1 for r in records if r.get("system_km"))
|
||||
n_built = sum(1 for r in records if r.get("built_km"))
|
||||
elev = [(r, elevation.get(r)) for r in records if elevation.get(r)]
|
||||
src = collections.Counter((e["source"].get("model", ""), e["source"].get("smoothing", ""),
|
||||
e["source"].get("sample_spacing_m")) for _, e in elev if e.get("source"))
|
||||
@@ -130,7 +132,8 @@ def method_page(records, site, repo_root):
|
||||
f"length was measured and checked against the published length."), [("Trails", "/"), ("About", "/about/")])
|
||||
+ f"""<div class="container section place"><div class="prose">
|
||||
<h2>Length</h2>
|
||||
<p>{esc(_sentence(meaning.get("length_km", "")))} It is the figure the trail’s holder or author gives, and each record says where it comes from. The lists and pages show it in miles with kilometres after.</p>
|
||||
<p>A trail’s length here is the end-to-end length of its canonical path: one walk from one end to the other, taking one branch at a split, leaving out side trails and counting no stretch twice. It is the figure the trail’s holder or author gives for that walk, and each record says where it comes from. A trail that cannot be walked from end to end today is not listed. The lists and pages show the length in miles with kilometres after.</p>
|
||||
<p>Some holders also publish a larger figure for a whole system, or a planned total. A record keeps it apart as the whole system, with what it counts, and no list, length band or time estimate uses it. {n_system} of the {n} records have one. A trail that can be walked through but is partly unbuilt keeps the holder’s end-to-end route as its length and gives the built length beside it. {n_built} of the {n} records give one.</p>
|
||||
<p>Where a track is included, its length is measured along the track as a geodesic length and compared with the published figure. The difference is the measured length minus the published length, as a percent of the published length. Track ends within 100 metres are joined, and the number of parts left is shown.</p>
|
||||
<p>Across the {len(ver)} measured tracks, the middle difference is {mid:.1f} percent.</p>
|
||||
{pagekit.table(["Measured against published", "Tracks", "Share"], rows, caption="How the measured tracks compare", numeric=(1, 2))}
|
||||
|
||||
@@ -178,9 +178,8 @@ def region_page(slug, records, site, facet_pages=()):
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
<div class="prose place-summary">{summary.facts(recs, records)}{standing_note}{summary.details(recs)}</div>
|
||||
{home.overview_map(recs, f"Map of the trails in {info['name']}")}
|
||||
{home.results(recs, top=2)}
|
||||
{home.place_grid(f'<div class="prose place-summary">{summary.facts(recs, records)}{standing_note}{summary.details(recs)}</div>',
|
||||
home.results(recs, top=2), home.overview_map(recs, f"Map of the trails in {info['name']}"))}
|
||||
{nav}
|
||||
</div>"""
|
||||
name = info["name"]
|
||||
@@ -236,6 +235,14 @@ def routes_page(records, site, repo_root=None, after="", author_pages=None):
|
||||
groups = [(f"By {author_pages[a]}" if a in author_pages else 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)
|
||||
intro = f"""<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’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’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>"""
|
||||
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>
|
||||
@@ -243,18 +250,7 @@ def routes_page(records, site, repo_root=None, after="", author_pages=None):
|
||||
<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">
|
||||
<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’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’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, top=2)}
|
||||
{home.place_grid(intro, home.results(groups=groups, routes_list=True, top=2), home.overview_map(routes, "Map of the routes with a GPX here"))}
|
||||
{after}
|
||||
<nav class="region-nav" aria-label="Other lists">{'<a href="/authors/">Route authors</a> · ' if linked else ""}<a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
|
||||
</div>"""
|
||||
@@ -286,10 +282,9 @@ def list_page(lst, recs, total, site, *, records=None, before="", after=""):
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
<div class="prose place-summary">{about}</div>
|
||||
{before}
|
||||
{home.overview_map(recs, f"Map of the trails in the list {lst.title}")}
|
||||
{home.results(recs, default_sort=lst.sort, top=2)}
|
||||
{home.place_grid(f'<div class="prose place-summary">{about}</div>', home.results(recs, default_sort=lst.sort, top=2),
|
||||
home.overview_map(recs, f"Map of the trails in the list {lst.title}"))}
|
||||
{after}
|
||||
<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>
|
||||
|
||||
@@ -56,7 +56,9 @@ def distribution():
|
||||
|
||||
# What the dataset records for each trail (docs/schema.md), as variableMeasured.
|
||||
VARIABLES = (
|
||||
("length_km", "Published length of the trail", "KMT"),
|
||||
("length_km", "End-to-end length of the trail's canonical path, as its holder or author states it", "KMT"),
|
||||
("system_km", "The larger figure the holder publishes for the whole system or a planned total, where there is one", "KMT"),
|
||||
("built_km", "The built length of an unfinished trail, as its holder states it", "KMT"),
|
||||
("measured_km", "Length measured from the track, in kilometres", "KMT"),
|
||||
("difference_percent", "Measured length against the published length, in per cent", "P1"),
|
||||
("ascent_m", "Total climbing along the track, computed from an elevation model", "MTR"),
|
||||
@@ -257,6 +259,16 @@ def _properties(rec):
|
||||
_pv("Published length", mi, "SMI", "miles", description=rec.get("length_note", "")),
|
||||
_pv("Published length", rec["length_km"], "KMT", "kilometres"),
|
||||
]
|
||||
if rec.get("system_km"):
|
||||
# The holder's larger figure: its own labelled value, never the trail's length.
|
||||
note = str(rec.get("system_note", "")).strip().rstrip(".")
|
||||
props.append(_pv("Whole system length", round(words.km_to_mi(rec["system_km"])), "SMI", "miles",
|
||||
description=f"Counting {note}"))
|
||||
props.append(_pv("Whole system length", rec["system_km"], "KMT", "kilometres",
|
||||
description=f"Counting {note}"))
|
||||
if rec.get("built_km"):
|
||||
props.append(_pv("Built length", round(words.km_to_mi(rec["built_km"])), "SMI", "miles"))
|
||||
props.append(_pv("Built length", rec["built_km"], "KMT", "kilometres"))
|
||||
days = h.get("days")
|
||||
if isinstance(days, list) and len(days) == 2:
|
||||
props.append(_pv("Usual time to walk it all", f"{days[0]} to {days[1]} days", "DAY", "days",
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""The static sketch: the tracks of a map, drawn into the page at build time.
|
||||
|
||||
A map frame is never empty. From the first paint it holds a light drawing of the track, on the
|
||||
plain ground, in the colours the live map uses (the .fallback__* rules of style.css), and the live
|
||||
map (app.js) takes over from it without a jump. For that the two must frame the same ground:
|
||||
|
||||
frame the extent of the tracks, widened on every side by PAD of its longer side, as
|
||||
[west, south, east, north] in degrees (data-frame on the figure). The drawing
|
||||
fits it exactly, and app.js opens the live map on the same box with no padding,
|
||||
so the track holds still when the base map arrives.
|
||||
|
||||
The drawing is an <svg> with a fixed viewBox (the frame, FIT units along its longer side) and
|
||||
preserveAspectRatio="xMidYMid meet", so it fits any frame size the way the live map fits the
|
||||
same bounds. Coordinates are Web Mercator, as the live map's. Each track is simplified to TOL
|
||||
units and written as whole numbers in one relative path: a few kilobytes for a trail, and a
|
||||
fixed, small size for the overview of every trail.
|
||||
|
||||
The tracks are read from the files the build has already written (trails/<id>/map.json,
|
||||
data/overview.geojson): the same simplified geometry the page ships to the live map.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
|
||||
from . import geo
|
||||
from .markup import Markup
|
||||
|
||||
FIT = 1200 # the longer side of the viewBox, in user units
|
||||
PAD = 0.07 # each side of the frame, as a share of the extent's longer side
|
||||
TOL = 1.1 # simplification, in viewBox units (about a pixel on a wide screen)
|
||||
MANY = 12 # a map of more tracks than this is drawn lighter: coarser, and with no halo
|
||||
TOL_MANY = 2.4
|
||||
MIN_SPAN = (0.5, 0.36) # degrees: a lone point or a tiny extent gets about a county of ground
|
||||
RAD = math.pi / 180.0
|
||||
EARTH_M = 6371008.8
|
||||
|
||||
DATA_DIR = "" # the site being built (olt/pages.py sets it); no data, no sketch
|
||||
_cache = {}
|
||||
|
||||
|
||||
def use(out_dir):
|
||||
"""Name the site directory the tracks are read from, and forget what was read before."""
|
||||
global DATA_DIR
|
||||
DATA_DIR = out_dir or ""
|
||||
_cache.clear()
|
||||
|
||||
|
||||
def _read(*parts):
|
||||
if not DATA_DIR:
|
||||
return None
|
||||
path = os.path.join(DATA_DIR, *parts)
|
||||
if path not in _cache:
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
_cache[path] = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
_cache[path] = None
|
||||
return _cache[path]
|
||||
|
||||
|
||||
def trail_features(trail_id):
|
||||
"""The features of one trail's map.json (main and alternates), or []."""
|
||||
fc = _read("trails", trail_id, "map.json") or _read("trails", trail_id, "sketch.json")
|
||||
return list(fc["features"]) if fc else []
|
||||
|
||||
|
||||
def overview_features(ids=None):
|
||||
"""The overview's features, limited to the trail ids given (all when None)."""
|
||||
fc = _read("data", "overview.geojson")
|
||||
if not fc:
|
||||
return []
|
||||
want = None if ids is None else set(ids)
|
||||
return [f for f in fc["features"] if want is None or (f.get("properties") or {}).get("id") in want]
|
||||
|
||||
|
||||
def _merc(lat):
|
||||
return math.log(math.tan(math.pi / 4 + lat * RAD / 2))
|
||||
|
||||
|
||||
def _unmerc(y):
|
||||
return math.degrees(2 * math.atan(math.exp(y)) - math.pi / 2)
|
||||
|
||||
|
||||
def frame(box):
|
||||
"""[west, south, east, north] of the ground a map frame shows for the extent `box`
|
||||
(the same box in degrees): widened by PAD, and given a minimum size."""
|
||||
w, s, e, n = box
|
||||
if e - w < 0.02:
|
||||
cx = (w + e) / 2
|
||||
w, e = cx - MIN_SPAN[0] / 2, cx + MIN_SPAN[0] / 2
|
||||
if n - s < 0.02:
|
||||
cy = (s + n) / 2
|
||||
s, n = cy - MIN_SPAN[1] / 2, cy + MIN_SPAN[1] / 2
|
||||
x0, x1 = w * RAD, e * RAD
|
||||
y0, y1 = _merc(s), _merc(n)
|
||||
pad = PAD * max(x1 - x0, y1 - y0)
|
||||
return [round((x0 - pad) / RAD, 5), round(_unmerc(y0 - pad), 5),
|
||||
round((x1 + pad) / RAD, 5), round(_unmerc(y1 + pad), 5)]
|
||||
|
||||
|
||||
def frame_attr(box):
|
||||
return ",".join(f"{v:g}" for v in frame(box))
|
||||
|
||||
|
||||
class Plane:
|
||||
"""Projects [lon, lat] into the viewBox of a frame."""
|
||||
|
||||
def __init__(self, fr):
|
||||
w, s, e, n = fr
|
||||
self.x0, self.x1 = w * RAD, e * RAD
|
||||
self.y0, self.y1 = _merc(s), _merc(n)
|
||||
span = max(self.x1 - self.x0, self.y1 - self.y0)
|
||||
self.k = FIT / span
|
||||
self.w = (self.x1 - self.x0) * self.k
|
||||
self.h = (self.y1 - self.y0) * self.k
|
||||
# metres on the ground per viewBox unit, at the middle of the frame
|
||||
mid = _unmerc((self.y0 + self.y1) / 2)
|
||||
self.m_per_unit = EARTH_M / self.k * math.cos(mid * RAD)
|
||||
|
||||
def xy(self, point):
|
||||
return ((point[0] * RAD - self.x0) * self.k, (self.y1 - _merc(point[1])) * self.k)
|
||||
|
||||
|
||||
def _path(plane, parts, tol=TOL):
|
||||
"""One relative SVG path for the parts: whole-number steps, simplified to tol units."""
|
||||
out = []
|
||||
for part in geo.simplify(geo.join_parts(parts), tol * plane.m_per_unit):
|
||||
pts = []
|
||||
for p in part:
|
||||
x, y = plane.xy(p)
|
||||
q = (round(x), round(y))
|
||||
if not pts or q != pts[-1]:
|
||||
pts.append(q)
|
||||
if len(pts) < 2:
|
||||
continue
|
||||
steps = " ".join(f"{b[0] - a[0]} {b[1] - a[1]}" for a, b in zip(pts, pts[1:]))
|
||||
out.append(f"M{pts[0][0]} {pts[0][1]}l{steps}")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _parts(feature):
|
||||
g = feature.get("geometry") or {}
|
||||
if g.get("type") == "LineString":
|
||||
return [g["coordinates"]]
|
||||
return list(g.get("coordinates") or []) if g.get("type") == "MultiLineString" else []
|
||||
|
||||
|
||||
def _points(feature):
|
||||
g = feature.get("geometry") or {}
|
||||
if g.get("type") == "Point":
|
||||
return [g["coordinates"]]
|
||||
return list(g.get("coordinates") or []) if g.get("type") == "MultiPoint" else []
|
||||
|
||||
|
||||
def svg(features, fr, *, route_main=False, ident=False):
|
||||
"""The sketch of these features on the frame `fr`, as Markup, or "" with nothing to draw.
|
||||
|
||||
route_main: a route page draws its main track in the route colour and dashed, as the map does.
|
||||
ident: write each trail's id on its paths (data-id), for the filters of an overview to hide them.
|
||||
"""
|
||||
if not features:
|
||||
return ""
|
||||
plane = Plane(fr)
|
||||
many = len(features) > MANY
|
||||
tol = TOL_MANY if many else TOL
|
||||
casings, lines, rings = [], [], []
|
||||
for f in features:
|
||||
props = f.get("properties") or {}
|
||||
rid = f' data-id="{props["id"]}"' if ident and props.get("id") else ""
|
||||
route = props.get("kind") == "route" or (route_main and (props.get("role") == "main" or props.get("sketch")))
|
||||
sketch = bool(props.get("sketch"))
|
||||
d = _path(plane, _parts(f), tol=tol if not sketch else 0.0)
|
||||
if d:
|
||||
if not sketch and not many:
|
||||
casings.append(f'<path class="fallback__casing" d="{d}"{rid}/>')
|
||||
mod = (" fallback__line--sketch" + (" fallback__line--sketch-route" if route else "")) if sketch \
|
||||
else " fallback__line--alternate" if props.get("role") == "alternate" \
|
||||
else " fallback__line--route" if route else ""
|
||||
lines.append(f'<path class="fallback__line{mod}" d="{d}"{rid}/>')
|
||||
for pt in _points(f):
|
||||
x, y = plane.xy(pt)
|
||||
cls = "fallback__ring" + (" fallback__ring--route" if props.get("kind") == "route" or route_main else "")
|
||||
rings.append(f'<circle class="{cls}" cx="{x:.0f}" cy="{y:.0f}" r="4"{rid}/>')
|
||||
if not lines and not rings:
|
||||
return ""
|
||||
return Markup(f'<svg class="map__sketch" viewBox="0 0 {plane.w:.2f} {plane.h:.2f}" '
|
||||
f'preserveAspectRatio="xMidYMid meet" aria-hidden="true" focusable="false">'
|
||||
f'{"".join(casings)}{"".join(lines)}{"".join(rings)}</svg>')
|
||||
@@ -128,7 +128,7 @@ def collection_page(collection, records, site):
|
||||
from . import home
|
||||
body = (pagekit.head(f"{name} trails compared", lede, [("Trails", "/"), ("Lists", "/lists/")])
|
||||
+ '<div class="container section place">'
|
||||
f'{pagekit.table(headers, rows, caption=f"The {name} trails side by side", row_heads=True)}'
|
||||
f'{pagekit.table(headers, rows, caption=f"The {name} trails side by side", row_heads=True, compare=True)}'
|
||||
f'{source}'
|
||||
f'<div class="prose place-summary">{summary.facts(recs, records)}</div>'
|
||||
f'{home.results(recs, top=2)}'
|
||||
|
||||
@@ -8,7 +8,7 @@ import os
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
from . import browse, common, elevation, facets, hike, related, seo, words
|
||||
from . import browse, common, elevation, facets, hike, related, seo, sketch, words
|
||||
from .layout import OUTDOOR_STYLE
|
||||
from .markup import Markup, esc
|
||||
|
||||
@@ -242,6 +242,15 @@ def permit_sentence(rec):
|
||||
return text
|
||||
|
||||
|
||||
def built_clause(rec):
|
||||
"""", with about 290 miles (467 km) built" for an unfinished trail whose holder states the built
|
||||
length; else "". HTML-safe text."""
|
||||
if not rec.get("built_km"):
|
||||
return ""
|
||||
mi = words.fmt_int(words.km_to_mi(rec["built_km"]))
|
||||
return f", with {esc(mi)} miles ({esc(words.fmt_km(rec['built_km']))} km) built"
|
||||
|
||||
|
||||
def brief_sentences(rec):
|
||||
"""The "In brief" paragraph as a list of sentences in HTML, from the record's own fields only.
|
||||
A fact the record lacks is left out. At most MAX_BRIEF sentences, in the order a searcher
|
||||
@@ -278,7 +287,7 @@ def brief_sentences(rec):
|
||||
article = "an" if mi.startswith("8") else "a" # "an 81-mile", "an 800-mile"
|
||||
through = f" through {country}" if country else ""
|
||||
items.append((0, 0, f"{_name_html(rec)} is {article} {esc(mi)}-mile ({esc(km)} km) {esc(noun)}"
|
||||
f"{esc(tail)}{esc(through)} {esc(place_text(rec))}."))
|
||||
f"{esc(tail)}{esc(through)} {esc(place_text(rec))}{built_clause(rec)}."))
|
||||
unfinished = common.sentence(h.get("unfinished", ""))
|
||||
if unfinished and unfinished not in hike.summary(rec): # the lede above may already say it
|
||||
items.append((4, 1, esc(unfinished)))
|
||||
@@ -360,9 +369,11 @@ def brief_sentences(rec):
|
||||
return [text for _, _, text in kept]
|
||||
|
||||
|
||||
def brief(rec):
|
||||
"""The "In brief" paragraph for the top of a trail page: Markup."""
|
||||
return Markup(f'<p class="trail-brief"><strong>In brief.</strong> {" ".join(brief_sentences(rec))}</p>')
|
||||
def brief(rec, label=True):
|
||||
"""The "In brief" paragraph of a trail: Markup. label: it opens with "In brief." (a trail page has
|
||||
its own "In brief" heading over it and leaves the label out)."""
|
||||
lead = "<strong>In brief.</strong> " if label else ""
|
||||
return Markup(f'<p class="trail-brief">{lead}{" ".join(brief_sentences(rec))}</p>')
|
||||
|
||||
|
||||
def checked_line(rec):
|
||||
@@ -393,8 +404,42 @@ def page_head(rec, author_links=None):
|
||||
heading = esc(common_name) if common_name else common.name(rec)
|
||||
full_name = f'<p class="titleblock__sub">Full name: {common.name(rec)}</p>' if common_name else ""
|
||||
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)
|
||||
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 page-head--trail">
|
||||
<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">
|
||||
{kicker}
|
||||
<h1>{heading}{abbr_html}</h1>
|
||||
{full_name}{f'<p class="titleblock__sub">{lead_html(rec, lead, author_links)}</p>' if lead else ""}
|
||||
{define}
|
||||
</div>
|
||||
</header>
|
||||
</div>
|
||||
</div>"""
|
||||
|
||||
|
||||
# The longest first sentence of the summary that stands above the map (about two lines beside the
|
||||
# At a glance panel); a longer one is left to the "In brief" section below the map.
|
||||
LEAD_MAX = 180
|
||||
|
||||
|
||||
def lead_text(rec):
|
||||
"""The line above the map: the first sentence of the summary, or "" when it is longer than LEAD_MAX
|
||||
(the whole summary is under the map either way). Markup."""
|
||||
one = hike.one_line(rec)
|
||||
if not one or len(one) > LEAD_MAX:
|
||||
return ""
|
||||
return Markup(f'<p class="trail-lede">{common.rich(one)}</p>')
|
||||
|
||||
|
||||
def action_buttons(rec):
|
||||
"""The buttons under the lead: the trail's own page, the GPX, Save."""
|
||||
actions = []
|
||||
official = official_link(rec)
|
||||
if official:
|
||||
@@ -409,29 +454,21 @@ def page_head(rec, author_links=None):
|
||||
else:
|
||||
actions.append(f'<a class="button button--quiet" href="#track">GPX: {esc(facets.GPX_STATUS[facets.gpx(rec)])}</a>')
|
||||
actions.append(str(common.save_button(rec, row=False)))
|
||||
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">
|
||||
{kicker}
|
||||
<h1>{heading}{abbr_html}</h1>
|
||||
{full_name}{f'<p class="titleblock__sub">{lead_html(rec, lead, author_links)}</p>' if lead else ""}
|
||||
{define}
|
||||
</div>
|
||||
</header>
|
||||
<p class="trail-lede">{lede}</p>
|
||||
{brief(rec)}
|
||||
{checked_line(rec)}
|
||||
<p class="cluster trail-actions">{"".join(actions)}</p>
|
||||
{links_panel(rec)}
|
||||
</div>
|
||||
</div>"""
|
||||
return f'<p class="cluster trail-actions">{"".join(actions)}</p>'
|
||||
|
||||
|
||||
def trail_text(rec):
|
||||
"""The words under the map area: the summary in full, the "In brief" paragraph, the date of the
|
||||
last check and the other pages about the trail. The text stays in the page for search engines."""
|
||||
summary = hike.summary(rec)
|
||||
lede = common.rich(summary) if summary else fallback_lede(rec)
|
||||
return f"""<section class="trail-text" aria-labelledby="brief-title">
|
||||
<h2 id="brief-title">In brief</h2>
|
||||
<p class="trail-summary">{lede}</p>
|
||||
{brief(rec, label=False)}
|
||||
{checked_line(rec)}
|
||||
</section>
|
||||
{links_panel(rec)}"""
|
||||
|
||||
|
||||
def shape_label(rec, records):
|
||||
@@ -468,6 +505,13 @@ def length_note(rec, records):
|
||||
return ""
|
||||
|
||||
|
||||
def length_asides(rec, records):
|
||||
"""What sits quietly under the length: the built figure of an unfinished trail, the holder's
|
||||
larger figure with what it counts, then the link to the list the length puts the trail in."""
|
||||
lines = [common.built_text(rec), common.system_text(rec), length_note(rec, records) or ""]
|
||||
return Markup("<br>".join(str(line) for line in lines if line))
|
||||
|
||||
|
||||
def time_note(rec, records):
|
||||
"""The estimate's note, then a link to the list of trails that take as long."""
|
||||
note = facets.estimate_note(rec)
|
||||
@@ -485,7 +529,7 @@ def glance(rec, records=None):
|
||||
lists they put the trail in (left out when None)."""
|
||||
h = hike.table(rec)
|
||||
rows = [glance_row(facets.LENGTH, words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]),
|
||||
length_note(rec, records))]
|
||||
length_asides(rec, records))]
|
||||
rows.append(glance_row(facets.TIME, facets.time_text(rec), time_note(rec, records)))
|
||||
season = facets.season_text(rec)
|
||||
if season:
|
||||
@@ -565,15 +609,27 @@ def glance(rec, records=None):
|
||||
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 ""
|
||||
# On a narrow screen only the first facts show (length and time first) and a button opens the
|
||||
# rest (style.css, app.js); with no JavaScript every fact shows.
|
||||
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}
|
||||
<button class="glance__toggle js-only" type="button" aria-expanded="false" data-glance-toggle>All the facts</button>
|
||||
</section>"""
|
||||
|
||||
|
||||
# Map or empty frame ---------------------------------------------------------
|
||||
|
||||
def sketch_of(box, features, route_main=False):
|
||||
"""(data-frame attribute, the static sketch) of a map frame for the extent `box`: the ground the
|
||||
live map opens on, and the drawing of the track on it (olt/sketch.py). Both are "" without a box."""
|
||||
if not box:
|
||||
return "", ""
|
||||
fr = sketch.frame(box)
|
||||
return f' data-frame="{",".join(f"{v:g}" for v in fr)}"', sketch.svg(features, fr, route_main=route_main)
|
||||
|
||||
|
||||
def map_figure(rec):
|
||||
src = rec["source"]
|
||||
has_alt = "alternates" in rec["derived"]["files"]
|
||||
@@ -583,12 +639,13 @@ def map_figure(rec):
|
||||
legend += f"<li>{common.SWATCH_ALT}Alternates and connectors</li>"
|
||||
bbox = rec["derived"].get("map_bbox") or rec["derived"].get("bbox")
|
||||
bbox_attr = f' data-bbox="{",".join(str(v) for v in bbox)}"' if bbox else ""
|
||||
frame_attr, drawing = sketch_of(bbox, sketch.trail_features(rec["id"]), route_main=route)
|
||||
credit = common.sentence(common.credit_text(src.get("attribution", "")))
|
||||
return f"""<figure class="mapfig mapfig--detail detail__map" data-map="trail" data-src="/trails/{esc(rec["id"])}/map.json" data-route="{"yes" if route else "no"}"{bbox_attr} data-outdoor="{OUTDOOR_STYLE}">
|
||||
return f"""<figure class="mapfig mapfig--detail detail__map" data-map="trail" data-src="/trails/{esc(rec["id"])}/map.json" data-route="{"yes" if route else "no"}"{bbox_attr}{frame_attr} data-outdoor="{OUTDOOR_STYLE}">
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
|
||||
<div class="map" role="region" aria-label="Map of the {esc(rec["name"])}">
|
||||
<div class="map__fallback"></div>
|
||||
<div class="map__fallback">{drawing}</div>
|
||||
<div class="map__canvas"></div>
|
||||
<p class="map__status" role="status">The map needs JavaScript. Download the GPX or GeoJSON file from this page.</p>
|
||||
</div>
|
||||
@@ -753,11 +810,12 @@ def sketch_figure(rec):
|
||||
legend_text = "No GPX here: start only"
|
||||
_title, status, reason, rule, actions_html = _no_gpx_parts(rec)
|
||||
reason_html = reason if isinstance(reason, Markup) else common.rich(reason)
|
||||
return f"""<figure class="mapfig mapfig--detail detail__map" id="track" data-map="sketch" data-src="/trails/{esc(rec["id"])}/sketch.json" data-route="{"yes" if route else "no"}"{bbox_attr} data-outdoor="{OUTDOOR_STYLE}">
|
||||
frame_attr, drawing = sketch_of(box, sketch.trail_features(rec["id"]), route_main=route)
|
||||
return f"""<figure class="mapfig mapfig--detail detail__map" id="track" data-map="sketch" data-src="/trails/{esc(rec["id"])}/sketch.json" data-route="{"yes" if route else "no"}"{bbox_attr}{frame_attr} data-outdoor="{OUTDOOR_STYLE}">
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
|
||||
<div class="map" role="region" aria-label="Map showing the start and end of the {esc(rec["name"])}; no GPX here">
|
||||
<div class="map__fallback"></div>
|
||||
<div class="map__fallback">{drawing}</div>
|
||||
<div class="map__canvas"></div>
|
||||
<p class="map__status" role="status">The map needs JavaScript. The ends of the trail are named below it.</p>
|
||||
</div>
|
||||
@@ -1072,8 +1130,15 @@ def record_block(rec):
|
||||
rows.append(fact("Inclusion", words.label(words.INCLUSION, inc), words.meaning(words.INCLUSION, inc)))
|
||||
rows += [
|
||||
Markup(f'<div><dt>Where</dt><dd>{where}</dd></div>'),
|
||||
Markup(f'<div><dt>Published length</dt><dd>{words.length(rec["length_km"], "inline", rec["derived"]["length_mi"])}'
|
||||
f'<small>{esc(rec.get("length_note", ""))}. A check value, not measured from the track.</small></dd></div>'),
|
||||
Markup(f'<div><dt>Length</dt><dd>{words.length(rec["length_km"], "inline", rec["derived"]["length_mi"])}'
|
||||
f'<small>{esc(common.sentence(rec.get("length_note", "")))} The end-to-end length of the trail’s '
|
||||
f'canonical path, a check value, not measured from the track.</small></dd></div>'),
|
||||
fact("Built length", common.built_text(rec), "How much of the trail is built, as the holder states it.")
|
||||
if rec.get("built_km") else "",
|
||||
fact("Whole system", Markup(f'{words.length(rec["system_km"], "inline")}, counting '
|
||||
f'{esc(str(rec["system_note"]).strip().rstrip("."))}'),
|
||||
"The holder's larger figure, kept apart from the length.")
|
||||
if rec.get("system_km") else "",
|
||||
abbreviation_fact(rec),
|
||||
fact("Record ID", Markup(code(rec["id"])), "Stable: the directory name, never changed"),
|
||||
]
|
||||
@@ -1539,7 +1604,10 @@ def description(rec):
|
||||
then the first sentence of the summary (or the designation where there is none)."""
|
||||
mi = words.fmt_int(rec["derived"]["length_mi"])
|
||||
km = words.fmt_km(rec["length_km"])
|
||||
text = f"A {kind_word(rec)} of {mi} miles ({km} km) {places_short(rec)}"
|
||||
built = ""
|
||||
if rec.get("built_km"):
|
||||
built = f", {words.fmt_int(words.km_to_mi(rec['built_km']))} miles built,"
|
||||
text = f"A {kind_word(rec)} of {mi} miles ({km} km){built} {places_short(rec)}"
|
||||
days = hike.days(rec)
|
||||
if days:
|
||||
text += f", usually {days}"
|
||||
@@ -1621,20 +1689,25 @@ def render(rec, site, records=None, author_links=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_track = common.has_line(rec)
|
||||
sketch = hike.sketch_points(rec) if not has_track else []
|
||||
has_map = has_track or bool(sketch)
|
||||
sketch_points = hike.sketch_points(rec) if not has_track else []
|
||||
has_map = has_track or bool(sketch_points)
|
||||
aside = downloads_panel(rec) + guides_panel(rec)
|
||||
aside_html = (f'<aside class="detail__aside" aria-label="{"Downloads" if has_track else "Where to get the route"}">'
|
||||
f'{aside}</aside>') if aside else ""
|
||||
profile = elevation_figure(rec)
|
||||
side = f'<div class="detail__side">{glance(rec, records)}{aside_html}</div>'
|
||||
body = f"""{page_head(rec, author_links)}
|
||||
<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, records)}
|
||||
{map_figure(rec) if has_track else sketch_figure(rec) if sketch else empty_frame(rec)}
|
||||
<div class="detail__lead">
|
||||
{lead_text(rec)}
|
||||
{action_buttons(rec)}
|
||||
</div>
|
||||
{side}
|
||||
{map_figure(rec) if has_track else sketch_figure(rec) if sketch_points else empty_frame(rec)}
|
||||
{profile}
|
||||
{aside_html}
|
||||
</div>
|
||||
<div class="container trail-more">
|
||||
{trail_text(rec)}
|
||||
{onward(rec, records)}
|
||||
{page_foot(rec, site)}
|
||||
{about_data(rec, site)}
|
||||
|
||||
@@ -43,7 +43,7 @@ WAVES = {
|
||||
"held": ("Held", "Listed, but something about it is not settled"),
|
||||
}
|
||||
INCLUSION = {
|
||||
"nst-unconditional": ("Listed unconditionally", "Every National Scenic Trail is listed"),
|
||||
"nst-unconditional": ("Listed as a National Scenic Trail", "A National Scenic Trail is listed unless it cannot be walked from one end to the other"),
|
||||
"candidate-decision-pending": ("Candidate", "The decision to list it is pending"),
|
||||
}
|
||||
KINDS = {
|
||||
|
||||
@@ -45,5 +45,4 @@ maintainer_url = "https://github.com/swaits"
|
||||
# so screen readers pronounce it in that language.
|
||||
[name_lang]
|
||||
traversee-charlevoix = "fr"
|
||||
sentier-national = "fr"
|
||||
sentier-international-appalaches = "fr"
|
||||
@@ -185,9 +185,9 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
# 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"'))
|
||||
# the map is in the tool, beside the list it filters (after it in the page, beside it on a wide screen)
|
||||
main = doc[doc.index('<div class="home__results">'):]
|
||||
self.assertLess(main.index('<ol class="entries" id="entries"'), main.index('data-map="overview"'))
|
||||
longest_km = max(r["length_km"] for r in self.records)
|
||||
maxsel = form[form.index('id="max"'):form.index("</select>", form.index('id="max"'))]
|
||||
minsel = form[form.index('id="min"'):form.index("</select>", form.index('id="min"'))]
|
||||
|
||||
@@ -242,7 +242,7 @@ def site_words(doc):
|
||||
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",
|
||||
for cls in ("entry__desc", "entry__name", "trail-lede", "trail-summary", "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
|
||||
@@ -285,10 +285,10 @@ class BuiltVocabularyTest(unittest.TestCase):
|
||||
self.maxDiff = None
|
||||
self.assertEqual(bad[:40], [])
|
||||
|
||||
def test_navigation_has_three_sections_and_saved(self):
|
||||
def test_navigation_has_four_sections_and_saved(self):
|
||||
doc = self.read("index.html")
|
||||
nav = re.search(r'<nav class="site-nav" aria-label="Main"><ul class="nav">(.*?)</ul></nav>', doc).group(1)
|
||||
self.assertEqual(re.findall(r'<li><a href="[^"]*"[^>]*>([^<]+)</a>', nav), ["Trails", "Places", "About"])
|
||||
self.assertEqual(re.findall(r'<li><a href="[^"]*"[^>]*>([^<]+)</a>', nav), ["Trails", "Places", "Lists", "About"])
|
||||
self.assertIn('<li class="nav__saved js-only"><a href="/saved/">', nav)
|
||||
|
||||
def test_one_count_noun(self):
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
"""The first screen: what the top of the trail page and the home page hold, the home page's lists
|
||||
(read from data), the header's Lists item, the tables that stack on a phone, and the maps' static
|
||||
drawings (olt/sketch.py) with the script's handover from them.
|
||||
|
||||
Pages are rendered one at a time; the site is not built. The sketch reads the track files of a
|
||||
site directory, so those are written to a temporary one here. The behaviour of the script in a
|
||||
browser was checked by driving the pages (see the changelog); these pin what its source promises.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
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.join(ROOT, "tools"))
|
||||
|
||||
from olt import browse, common, datafiles, home, layout, pagekit, records, site, sketch, trail # noqa: E402
|
||||
|
||||
SITE = site.load()
|
||||
|
||||
|
||||
def read(*parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def load(tid):
|
||||
return records.load_record(ROOT, tid)
|
||||
|
||||
|
||||
class HomePageTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.recs = records.load_records(ROOT)
|
||||
cls.body = home.render(cls.recs, SITE, ROOT)
|
||||
|
||||
def test_the_hero_no_longer_repeats_the_site_mark_or_the_strip_of_words(self):
|
||||
hero = self.body[:self.body.index('class="container home"')]
|
||||
self.assertNotIn("lockup", hero)
|
||||
self.assertNotIn("hero__tags", hero)
|
||||
self.assertNotIn("<img", hero)
|
||||
self.assertIn("<h1", hero)
|
||||
self.assertIn(SITE.tagline.rstrip("."), hero)
|
||||
|
||||
def test_the_header_shows_the_name_on_the_home_page(self):
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertNotIn(".hero--home) .site-header .wordmark", css)
|
||||
|
||||
def test_the_lists_row_is_read_from_the_data_file_in_its_order(self):
|
||||
entries = datafiles.lists(ROOT)
|
||||
keys = home.home_picks(entries)
|
||||
self.assertEqual(keys, ["national-scenic-trails", "routes", "high-routes", "loops", "under-100-miles",
|
||||
"a-week-or-less", "one-to-two-weeks", "a-month-or-more", "with-gpx", "canada"])
|
||||
row = home.lists_row(self.recs, keys)
|
||||
titles = re.findall(r'<li><a href="[^"]+">(.*?) <span class="chips__n">', row)
|
||||
self.assertEqual(titles, [browse.by_key(k).title for k in keys])
|
||||
self.assertTrue(row.rstrip().endswith("</nav>"))
|
||||
self.assertIn('<a href="/lists/">All lists</a>', row)
|
||||
self.assertNotIn("Hiking in", row)
|
||||
# a different file gives a different row: the set is not a constant of the generator
|
||||
other = home.home_picks([{"key": "loops", "home": 2}, {"key": "routes", "home": 1}, {"key": "canada"}])
|
||||
self.assertEqual(other, ["routes", "loops"])
|
||||
self.assertEqual(re.findall(r'<li><a href="[^"]+">(.*?) <span', home.lists_row(self.recs, other)), ["Routes", "Loops"])
|
||||
|
||||
def test_search_and_filters_are_one_bar_with_a_clear_control_that_starts_hidden(self):
|
||||
bar = self.body[self.body.index('class="filters__bar"'):self.body.index('id="filters-panels"')]
|
||||
self.assertIn('id="q"', bar)
|
||||
self.assertIn('aria-controls="filters-panels"', bar)
|
||||
self.assertRegex(bar, r'class="button button--quiet filters__clear" type="reset" hidden')
|
||||
self.assertIn('id="filters-panels"', self.body)
|
||||
self.assertIn('class="filters__panel"', self.body)
|
||||
self.assertIn('class="filters__more"', self.body)
|
||||
|
||||
def test_the_results_precede_the_map_in_the_page_and_the_map_has_its_own_address(self):
|
||||
self.assertLess(self.body.index('class="home__results"'), self.body.index('class="home__map"'))
|
||||
self.assertIn('id="map"', self.body)
|
||||
|
||||
def test_the_stylesheet_puts_the_map_beside_the_list_on_a_wide_screen(self):
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertRegex(css, r"\.home \{[^}]*grid-template-areas: \"lists\" \"bar\" \"results\" \"map\" \"notes\"")
|
||||
self.assertIn('grid-template-areas: "lists lists" "bar map" "results map" "notes ."', css)
|
||||
self.assertRegex(css, r"\.lists-row \.chips \{[^}]*flex-wrap: nowrap; overflow-x: auto")
|
||||
|
||||
|
||||
class ListEntriesCheckTest(unittest.TestCase):
|
||||
def check(self, entries, keys=("a", "b", "c")):
|
||||
import check_datafiles
|
||||
errors = []
|
||||
check_datafiles.check_list_entries(entries, set(keys), errors)
|
||||
return errors
|
||||
|
||||
def test_the_real_entries_pass(self):
|
||||
import check_datafiles
|
||||
errors = []
|
||||
import tomllib
|
||||
with open(os.path.join(ROOT, "collections.toml"), "rb") as f:
|
||||
doc = tomllib.load(f)
|
||||
check_datafiles.check_list_entries(doc["list"], check_datafiles.built_in_list_keys(), errors)
|
||||
self.assertEqual(errors, [])
|
||||
|
||||
def test_unknown_keys_repeats_and_bad_positions_are_reported(self):
|
||||
self.assertEqual(self.check([{"key": "a", "home": 1}, {"key": "b", "home": 2}]), [])
|
||||
self.assertTrue(any("not the key of a list" in e for e in self.check([{"key": "zzz", "home": 1}])))
|
||||
self.assertTrue(any("appears twice" in e for e in self.check([{"key": "a", "home": 1}, {"key": "a", "home": 2}])))
|
||||
self.assertTrue(any("also the place of" in e for e in self.check([{"key": "a", "home": 1}, {"key": "b", "home": 1}])))
|
||||
self.assertTrue(any("whole number" in e for e in self.check([{"key": "a", "home": 0}])))
|
||||
self.assertTrue(any("whole number" in e for e in self.check([{"key": "a", "home": "1"}])))
|
||||
self.assertTrue(any("unknown field" in e for e in self.check([{"key": "a", "shown": 1}])))
|
||||
|
||||
|
||||
class HeaderTest(unittest.TestCase):
|
||||
def nav(self, path):
|
||||
html = str(layout.header(path, SITE))
|
||||
return {m.group(2): m.group(1) for m in re.finditer(r'<a href="(/[^"]*)"(?: aria-current="[a-z]+")?>', html)}, html
|
||||
|
||||
def current(self, path):
|
||||
html = str(layout.header(path, SITE))
|
||||
return re.findall(r'<a href="([^"]+)" aria-current="(?:page|true)"', html)
|
||||
|
||||
def test_the_items_are_trails_places_lists_about_saved(self):
|
||||
html = str(layout.header("/", SITE))
|
||||
names = re.findall(r"<li[^>]*><a [^>]*>(?:<svg.*?</svg>)?([A-Za-z]+)", html)
|
||||
self.assertEqual(names[:5], ["Trails", "Places", "Lists", "About", "Saved"])
|
||||
self.assertIn('<a href="/lists/">Lists</a>', html)
|
||||
|
||||
def test_lists_is_current_on_the_index_lists_tables_and_views(self):
|
||||
for path in ("/lists/", "/lists/loops/", "/routes/", "/numbers/", "/numbers/highest-points/", "/authors/",
|
||||
"/authors/andrew-skurka/", "/recent/", "/connected/"):
|
||||
self.assertEqual(self.current(path), ["/lists/"], path)
|
||||
layout.UNDER_LISTS.add("/triple-crown/")
|
||||
try:
|
||||
self.assertEqual(self.current("/triple-crown/"), ["/lists/"])
|
||||
finally:
|
||||
layout.UNDER_LISTS.discard("/triple-crown/")
|
||||
|
||||
def test_the_other_items_keep_their_pages(self):
|
||||
self.assertEqual(self.current("/"), ["/"])
|
||||
self.assertEqual(self.current("/trails/tonto-trail/"), ["/"])
|
||||
self.assertEqual(self.current("/regions/us-co/"), ["/regions/"])
|
||||
self.assertEqual(self.current("/regions/us-co/loops/"), ["/regions/"])
|
||||
self.assertEqual(self.current("/about/"), ["/about/"])
|
||||
self.assertEqual(self.current("/sources/"), ["/about/"])
|
||||
self.assertEqual(self.current("/glossary/"), ["/about/"])
|
||||
|
||||
def test_the_triple_crown_page_is_listed_under_lists_by_the_page_builder(self):
|
||||
self.assertIn("layout.UNDER_LISTS.add(path)", read(WEB, "olt", "pages.py"))
|
||||
|
||||
|
||||
class TablesTest(unittest.TestCase):
|
||||
def test_every_cell_carries_its_label_and_a_wide_table_is_set_by_row(self):
|
||||
t = str(pagekit.table(["Trail", "Length", "States", "Time"], [["A", "1", "X", "2"]], caption="c"))
|
||||
self.assertIn('<table data-stack="rows">', t)
|
||||
self.assertEqual(re.findall(r'data-label="([^"]+)"', t), ["Trail", "Length", "States", "Time"])
|
||||
small = str(pagekit.table(["A", "B", "C"], [["1", "2", "3"]]))
|
||||
self.assertNotIn("data-stack", small)
|
||||
|
||||
def test_a_compare_table_labels_each_cell_with_its_row_and_stacks_by_column(self):
|
||||
t = str(pagekit.table(["Figure", "AT", "PCT"], [["Length", "2,198", "2,650"], ["States", "14", "3"]],
|
||||
row_heads=True, compare=True))
|
||||
self.assertIn('<table data-stack="columns">', t)
|
||||
self.assertEqual(re.findall(r'<td data-label="([^"]+)"', t), ["Length", "Length", "States", "States"])
|
||||
|
||||
def test_the_triple_crown_table_is_a_compare_table_with_equal_columns(self):
|
||||
from olt import standing
|
||||
recs = records.load_records(ROOT)
|
||||
c = datafiles.collections(ROOT)[0]
|
||||
title, desc, body, _ = standing.collection_page(c, recs, SITE)
|
||||
self.assertIn('data-stack="columns"', str(body))
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertIn('table[data-stack="columns"] { table-layout: fixed;', css)
|
||||
self.assertIn('th:first-child { inline-size: 9rem; }', css)
|
||||
self.assertIn("order: 3", css) # one block per trail on a phone, from the same cells
|
||||
self.assertNotIn("min-inline-size: 34rem !important", css)
|
||||
|
||||
def test_the_left_out_tables_stack_on_a_phone_too(self):
|
||||
src = read(WEB, "olt", "leftout.py")
|
||||
self.assertIn('<table data-stack="rows">', src)
|
||||
self.assertEqual(src.count("data-label="), 6)
|
||||
|
||||
|
||||
class SketchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
os.makedirs(os.path.join(self.dir.name, "trails", "x"))
|
||||
coords = [[-112.0 + i * 0.001, 36.0 + (i % 7) * 0.0004 + i * 0.0005] for i in range(400)]
|
||||
fc = {"type": "FeatureCollection", "features": [
|
||||
{"type": "Feature", "properties": {"role": "main"}, "geometry": {"type": "MultiLineString", "coordinates": [coords]}}]}
|
||||
with open(os.path.join(self.dir.name, "trails", "x", "map.json"), "w") as f:
|
||||
json.dump(fc, f)
|
||||
sketch.use(self.dir.name)
|
||||
self.box = [-112.0, 36.0, -111.6, 36.2]
|
||||
|
||||
def tearDown(self):
|
||||
sketch.use("")
|
||||
self.dir.cleanup()
|
||||
|
||||
def test_the_drawing_is_light_and_in_the_site_s_track_classes(self):
|
||||
fr = sketch.frame(self.box)
|
||||
svg = str(sketch.svg(sketch.trail_features("x"), fr))
|
||||
self.assertLess(len(svg), 4000)
|
||||
self.assertIn('class="map__sketch"', svg)
|
||||
self.assertIn('class="fallback__casing"', svg)
|
||||
self.assertIn('class="fallback__line"', svg)
|
||||
self.assertIn('preserveAspectRatio="xMidYMid meet"', svg)
|
||||
self.assertNotRegex(svg, r"\d\.\d{3,}") # whole numbers, relative steps
|
||||
self.assertRegex(svg, r'd="M\d+ \d+l')
|
||||
|
||||
def test_the_frame_is_the_extent_widened_on_every_side(self):
|
||||
w, s, e, n = sketch.frame(self.box)
|
||||
self.assertLess(w, self.box[0])
|
||||
self.assertLess(s, self.box[1])
|
||||
self.assertGreater(e, self.box[2])
|
||||
self.assertGreater(n, self.box[3])
|
||||
|
||||
def test_the_viewbox_has_the_frames_proportions_so_both_fit_a_container_the_same_way(self):
|
||||
import math
|
||||
fr = sketch.frame(self.box)
|
||||
svg = str(sketch.svg(sketch.trail_features("x"), fr))
|
||||
vw, vh = map(float, re.search(r'viewBox="0 0 ([\d.]+) ([\d.]+)"', svg).groups())
|
||||
merc = lambda lat: math.log(math.tan(math.pi / 4 + math.radians(lat) / 2))
|
||||
want = (math.radians(fr[2] - fr[0])) / (merc(fr[3]) - merc(fr[1]))
|
||||
self.assertAlmostEqual(vw / vh, want, places=3)
|
||||
|
||||
def test_a_trail_page_carries_the_frame_and_the_drawing(self):
|
||||
rec = load("tonto-trail")
|
||||
rec["id"] = "x"
|
||||
rec["derived"]["bbox"] = self.box
|
||||
rec["derived"]["files"] = {"line": "x.gpx"}
|
||||
fig = trail.map_figure(rec)
|
||||
self.assertRegex(fig, r'data-frame="-?[\d.]+,-?[\d.]+,-?[\d.]+,-?[\d.]+"')
|
||||
self.assertIn('<div class="map__fallback"><svg class="map__sketch"', fig)
|
||||
self.assertIn('class="map__status"', fig) # the no-script text stays
|
||||
|
||||
def test_no_data_no_drawing_and_no_empty_placeholder_text_for_scripts(self):
|
||||
sketch.use("")
|
||||
rec = load("tonto-trail")
|
||||
rec["derived"]["bbox"] = self.box
|
||||
self.assertIn('<div class="map__fallback"></div>', trail.map_figure(rec))
|
||||
|
||||
|
||||
class HandoverTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.js = read(WEB, "assets", "app.js")
|
||||
cls.css = read(WEB, "assets", "style.css")
|
||||
|
||||
def test_the_live_map_opens_on_the_drawings_ground_with_no_padding(self):
|
||||
self.assertIn("var frame = (fig.dataset.frame || '').split(',').map(Number);", self.js)
|
||||
self.assertIn("options.bounds = [[frame[0], frame[1]], [frame[2], frame[3]]];", self.js)
|
||||
self.assertIn("options.fitBoundsOptions = { padding: 0 };", self.js)
|
||||
|
||||
def test_nothing_is_drawn_over_the_page_s_own_drawing_and_no_placeholder_text_is_written(self):
|
||||
self.assertIn("if (hasSketch()) { sketchCorners(); return; }", self.js)
|
||||
self.assertNotIn("The map loads when you scroll to it.", self.js)
|
||||
self.assertNotIn("Loading the track", self.js)
|
||||
self.assertNotIn("Loading the base map", self.js)
|
||||
self.assertIn("html.js .map__status:not([data-say]) { display: none; }", self.css)
|
||||
|
||||
def test_the_drawing_gives_way_after_the_first_frame_with_the_tracks_and_a_fade(self):
|
||||
self.assertIn("map.once('render', reveal);", self.js)
|
||||
self.assertIn("map.isSourceLoaded('olt')", self.js)
|
||||
self.assertIn(".map[data-state=\"ready\"] .map__fallback { visibility: hidden; transition: visibility 0s 0.4s; }", self.css)
|
||||
self.assertIn(".map__canvas { opacity: 0; transition: opacity 0.4s ease; }", self.css)
|
||||
|
||||
def test_every_frame_starts_when_the_page_is_idle_whatever_its_place(self):
|
||||
self.assertIn("requestIdleCallback(begin, { timeout: 500 })", self.js)
|
||||
self.assertNotIn("IntersectionObserver", self.js)
|
||||
self.assertNotIn("MAP_AHEAD", self.js)
|
||||
|
||||
def test_the_first_view_of_an_overview_needs_no_move(self):
|
||||
self.assertIn("if (entry.frame && same) { target = entry.frame; padding = 0; }", self.js)
|
||||
|
||||
|
||||
class PageTopsTest(unittest.TestCase):
|
||||
def test_a_place_or_list_page_puts_its_list_before_the_text_and_the_map_in_the_narrow_order(self):
|
||||
grid = home.place_grid("TEXT", "LIST", "MAP")
|
||||
self.assertLess(grid.index("TEXT"), grid.index("LIST")) # the text is first in the page
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertIn('grid-template-areas: "list" "map" "text";', css)
|
||||
self.assertIn('grid-template-areas: "list text" "list map";', css)
|
||||
|
||||
def test_every_page_head_is_compact(self):
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertRegex(css, r"\.page-head \.titleblock h1 \{ font-size: var\(--step-3\)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -114,7 +114,7 @@ class HistorySectionTest(unittest.TestCase):
|
||||
|
||||
def test_real_records_all_show_their_history(self):
|
||||
recs = records.load_records()
|
||||
self.assertEqual(len(recs), 204)
|
||||
self.assertEqual(len(recs), 196)
|
||||
for rec in recs:
|
||||
part = trail.history_section(rec)
|
||||
self.assertIn("History of this record", part, rec["id"])
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Tests for the length facts on a trail page: the canonical length, the holder's larger figure
|
||||
and the built length of an unfinished trail (docs/schema.md, "What length_km counts").
|
||||
|
||||
These render fixtures; they do not need the built site.
|
||||
"""
|
||||
import copy
|
||||
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, common, facets, seo, site, trail, words # noqa: E402
|
||||
from test_hike import FULL_HIKE, GH, fake, render, top_part # noqa: E402
|
||||
from test_hike import text as _text # noqa: E402
|
||||
|
||||
def text(fragment):
|
||||
"""The words of a fragment, with the space the tags add before a comma taken out."""
|
||||
return _text(fragment).replace(" ,", ",")
|
||||
|
||||
|
||||
NOTE = "all designated trail, official side trail and connecting roadwalks"
|
||||
|
||||
|
||||
def with_lengths(i, km, **more):
|
||||
rec = fake(i, km=km, hike=copy.deepcopy(FULL_HIKE))
|
||||
rec["derived"]["length_mi"] = round(km / words.KM_PER_MI)
|
||||
rec.update(more)
|
||||
return rec
|
||||
|
||||
|
||||
def florida():
|
||||
rec = with_lengths(1, 1818, system_km=2549, system_note=NOTE)
|
||||
del rec["hike"]["unfinished"]
|
||||
return rec
|
||||
|
||||
|
||||
def unfinished():
|
||||
return with_lengths(2, 523, built_km=467)
|
||||
|
||||
|
||||
def glance_length(rec):
|
||||
body = top_part(render(rec))
|
||||
start = body.index('<dt>Length</dt>')
|
||||
return body[start:body.index("</div>", start)]
|
||||
|
||||
|
||||
class GlanceTest(unittest.TestCase):
|
||||
def test_the_length_is_the_canonical_one_and_the_system_figure_sits_beneath_it(self):
|
||||
row = glance_length(florida())
|
||||
self.assertIn('<span class="len__mi">1,130 mi</span><span class="len__km">1,818 km</span>', row)
|
||||
self.assertIn(f"Whole system: 1,584 mi 2,549 km, counting {NOTE}", text(row))
|
||||
self.assertLess(row.index("len--stack"), row.index("Whole system"))
|
||||
self.assertIn("<small>", row)
|
||||
|
||||
def test_the_built_figure_sits_beneath_the_length(self):
|
||||
row = glance_length(unfinished())
|
||||
self.assertIn('<span class="len__mi">325 mi</span><span class="len__km">523 km</span>', row)
|
||||
self.assertIn("290 mi 467 km built", text(row))
|
||||
self.assertNotIn("Whole system", row)
|
||||
|
||||
def test_a_record_with_neither_shows_neither(self):
|
||||
row = glance_length(with_lengths(3, 523))
|
||||
self.assertNotIn("built", row)
|
||||
self.assertNotIn("Whole system", row)
|
||||
|
||||
def test_both_may_show_together_and_the_note_is_escaped(self):
|
||||
rec = with_lengths(4, 523, built_km=467, system_km=700, system_note="side trails <b>too</b>")
|
||||
row = glance_length(rec)
|
||||
self.assertIn("built", row)
|
||||
self.assertIn("counting side trails <b>too</b>", row)
|
||||
|
||||
def test_the_not_finished_panel_still_follows_the_unfinished_sentence(self):
|
||||
body = top_part(render(unfinished()))
|
||||
self.assertIn("<strong>Not finished.</strong>", body)
|
||||
|
||||
|
||||
class BriefAndDescriptionTest(unittest.TestCase):
|
||||
def test_in_brief_uses_the_canonical_length_and_may_add_the_built_figure(self):
|
||||
first = text(trail.brief_sentences(florida())[0])
|
||||
self.assertIn("1,130-mile (1,818 km)", first)
|
||||
self.assertNotIn("1,584", first)
|
||||
self.assertNotIn("built", first)
|
||||
first = text(trail.brief_sentences(unfinished())[0])
|
||||
self.assertIn("325-mile (523 km)", first)
|
||||
self.assertIn("with 290 miles (467 km) built", first)
|
||||
|
||||
def test_the_description_uses_the_canonical_length(self):
|
||||
self.assertIn("1,130 miles (1,818 km)", trail.description(florida()))
|
||||
self.assertNotIn("1,584", trail.description(florida()))
|
||||
self.assertIn("325 miles (523 km), 290 miles built,", trail.description(unfinished()))
|
||||
self.assertLessEqual(len(trail.description(unfinished())), common.DESCRIPTION_LIMIT)
|
||||
|
||||
|
||||
class StructuredDataTest(unittest.TestCase):
|
||||
def props(self, rec):
|
||||
return {(p["name"], p.get("unitCode")): p for p in seo.place_node(rec, GH)["additionalProperty"]}
|
||||
|
||||
def test_the_length_stays_canonical_and_the_system_figure_is_labelled(self):
|
||||
props = self.props(florida())
|
||||
self.assertEqual(props[("Published length", "KMT")]["value"], 1818)
|
||||
self.assertEqual(props[("Published length", "SMI")]["value"], 1130)
|
||||
self.assertEqual(props[("Whole system length", "KMT")]["value"], 2549)
|
||||
self.assertEqual(props[("Whole system length", "SMI")]["value"], 1584)
|
||||
self.assertEqual(props[("Whole system length", "SMI")]["description"], f"Counting {NOTE}")
|
||||
self.assertNotIn(("Built length", "KMT"), props)
|
||||
|
||||
def test_the_built_length_is_labelled_and_a_plain_record_has_neither(self):
|
||||
props = self.props(unfinished())
|
||||
self.assertEqual(props[("Built length", "KMT")]["value"], 467)
|
||||
self.assertEqual(props[("Built length", "SMI")]["value"], 290)
|
||||
self.assertNotIn(("Whole system length", "KMT"), props)
|
||||
props = self.props(with_lengths(5, 523))
|
||||
self.assertFalse([k for k in props if k[0] in ("Built length", "Whole system length")])
|
||||
|
||||
|
||||
class OnlyTheCanonicalLengthCountsTest(unittest.TestCase):
|
||||
def test_bands_time_estimates_and_lists_ignore_the_larger_figure(self):
|
||||
plain, big = with_lengths(6, 1818), florida()
|
||||
for rec in (plain, big):
|
||||
del rec["hike"]["days"]
|
||||
self.assertEqual(facets.time_days(plain), facets.time_days(big))
|
||||
self.assertEqual(facets.time_band(plain), facets.time_band(big))
|
||||
for key in ("under-100-miles", "longest"):
|
||||
self.assertEqual(browse.by_key(key).test(plain), browse.by_key(key).test(big), key)
|
||||
# the band follows length_km: raising only the system figure moves nothing
|
||||
longer = copy.deepcopy(big)
|
||||
longer["system_km"] = 9000
|
||||
self.assertEqual(facets.time_days(big), facets.time_days(longer))
|
||||
|
||||
def test_the_record_panel_names_both_figures_apart(self):
|
||||
body = render(florida())
|
||||
panel = text(body[body.index('id="record-title"'):])
|
||||
self.assertIn("Length 1,130 mi 1,818 km", panel)
|
||||
self.assertIn("Whole system 1,584 mi 2,549 km, counting", panel)
|
||||
panel = text(render(unfinished())[render(unfinished()).index('id="record-title"'):])
|
||||
self.assertIn("Built length 290 mi 467 km built", panel)
|
||||
|
||||
|
||||
class WordsTest(unittest.TestCase):
|
||||
def test_the_glossary_and_the_method_page_say_what_length_means(self):
|
||||
import tomllib
|
||||
with open(os.path.join(os.path.dirname(WEB), "glossary.toml"), "rb") as f:
|
||||
terms = {t["id"]: t for t in tomllib.load(f)["term"]}
|
||||
definition = terms["published-length"]["definition"]
|
||||
self.assertIn("end-to-end length", definition)
|
||||
self.assertIn("canonical path", definition)
|
||||
self.assertIn("no system total", definition)
|
||||
|
||||
def test_the_schema_defines_length_and_names_the_new_fields(self):
|
||||
with open(os.path.join(os.path.dirname(WEB), "docs", "schema.md"), encoding="utf-8") as f:
|
||||
schema = f.read()
|
||||
for needle in ("What `length_km` counts", "`system_km`", "`system_note`", "`built_km`",
|
||||
"canonical path", "Florida"):
|
||||
self.assertIn(needle, schema)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,6 +1,7 @@
|
||||
"""The maps start late: nothing for a map (MapLibre, its style, the contour add-on, the track
|
||||
data) loads with the page. These pin the script's promises (the script has no unit tests; the
|
||||
behaviour was checked by driving the pages in a browser)."""
|
||||
"""The maps start a moment after the page has loaded, every one of them, by itself. Nothing for a
|
||||
map (MapLibre, its style, the contour add-on, the track data) loads with the page, and nothing
|
||||
waits for a scroll, a tap, a key or focus. These pin the script's promises (the script has no unit
|
||||
tests; the behaviour was checked by driving the pages in a browser)."""
|
||||
import os
|
||||
import re
|
||||
import unittest
|
||||
@@ -19,23 +20,41 @@ class MapStartTest(unittest.TestCase):
|
||||
cls.js = read("assets", "app.js")
|
||||
|
||||
def test_one_function_starts_a_map_and_it_is_the_only_caller_of_the_fetch_and_the_loader(self):
|
||||
self.assertEqual(self.js.count("fetchData()"), 2) # its definition and the one call
|
||||
self.assertEqual(self.js.count("fetchData()"), 3) # its definition, begin(), and a frame with no drawing
|
||||
self.assertEqual(self.js.count("loadLibraries()"), 2)
|
||||
begin = re.search(r"function begin\(\) \{(.*?)\n \}\n", self.js, re.S)
|
||||
self.assertIsNotNone(begin)
|
||||
self.assertIn("dataReady = fetchData();", begin.group(1))
|
||||
self.assertIn("dataReady = dataReady || fetchData();", begin.group(1))
|
||||
self.assertIn("loadLibraries().then(startMapLibre);", begin.group(1))
|
||||
self.assertIn("if (outdoorUrl) fetchOutdoor(outdoorUrl);", begin.group(1))
|
||||
self.assertEqual(self.js.count("fetchOutdoor(outdoorUrl)"), 2) # begin() and startMapLibre(), once started
|
||||
|
||||
def test_a_map_starts_when_near_the_screen_or_touched_never_at_once(self):
|
||||
self.assertIn("new IntersectionObserver(", self.js)
|
||||
self.assertIn("afterLoad(begin);", self.js) # near the screen, and the page has loaded
|
||||
for event in ("pointerdown", "focusin", "keydown"):
|
||||
self.assertIn(f"'{event}'", self.js)
|
||||
def start_code(self):
|
||||
code = re.search(r"function begin\(\) \{.*?\n function entryFor", self.js, re.S).group(0)
|
||||
return re.sub(r"/\*.*?\*/", "", code, flags=re.S) # the code, not the comments
|
||||
|
||||
def test_every_map_starts_by_itself_after_the_load_event_and_nothing_else_starts_it(self):
|
||||
code = self.start_code()
|
||||
self.assertIn("window.addEventListener('load', fn, { once: true })", code)
|
||||
self.assertIn("requestIdleCallback(begin, { timeout: 500 })", code)
|
||||
self.assertIn("setTimeout(begin, 100)", code)
|
||||
self.assertEqual(len(re.findall(r"\bbegin\b", code)), 3) # its definition and those two calls, no other trigger
|
||||
|
||||
def test_no_map_waits_for_visibility_or_for_the_visitor(self):
|
||||
# the whole script: no observer of any kind, and no scroll listener
|
||||
for word in ("IntersectionObserver", "ResizeObserver", "MAP_AHEAD", "isIntersecting", "'scroll'", "'touchstart'"):
|
||||
self.assertNotIn(word, self.js)
|
||||
code = self.start_code()
|
||||
for event in ("pointerdown", "pointerup", "focusin", "focus", "keydown", "keyup", "click", "mouseover", "touch", "wheel"):
|
||||
self.assertNotIn(event, code)
|
||||
self.assertNotIn("addEventListener('" , code.replace("window.addEventListener('load'", ""))
|
||||
self.assertNotIn("startMaps", self.js)
|
||||
self.assertNotRegex(self.js, r"initMap\(fig\)[^}]*\n\s*(fetch|loadLibraries)")
|
||||
|
||||
def test_a_frame_with_no_drawing_of_its_own_is_drawn_from_the_data_at_once(self):
|
||||
# the saved trails are known only to the browser: no drawing is made when the site is built
|
||||
self.assertIn("if (!hasSketch()) dataReady = fetchData();", self.js)
|
||||
|
||||
def test_the_libraries_come_from_the_addresses_on_the_scripts_own_tag(self):
|
||||
self.assertIn("var SCRIPT = document.currentScript;", self.js)
|
||||
for attr in ("maplibreCss", "maplibreJs", "contourJs"):
|
||||
@@ -48,8 +67,11 @@ class MapStartTest(unittest.TestCase):
|
||||
# the page runs the scripts in order: the add-on needs MapLibre first
|
||||
self.assertIn("script.async = false;", self.js)
|
||||
|
||||
def test_until_it_starts_the_frame_says_what_happens_and_the_page_text_stays_for_no_script(self):
|
||||
self.assertIn("'The map loads when you scroll to it.'", self.js)
|
||||
def test_until_it_starts_the_frame_holds_its_drawing_and_says_nothing_with_a_script(self):
|
||||
# the page's own drawing fills the frame (test_first_screen.py); the no-script text is shown
|
||||
# only without JavaScript, or when a failure sets data-say
|
||||
self.assertNotIn("The map loads when you scroll to it.", self.js)
|
||||
self.assertIn("function say(text) {", self.js)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -394,7 +394,7 @@ class RealDocumentsTest(unittest.TestCase):
|
||||
counter = TableCounter()
|
||||
counter.feed(md.render(read_doc("README.md")))
|
||||
counter.close()
|
||||
self.assertEqual(counter.counts, [147, 57])
|
||||
self.assertEqual(counter.counts, [139, 57])
|
||||
|
||||
def test_readme_num_class_present(self):
|
||||
self.assertIn('class="num"', md.render(read_doc("README.md")))
|
||||
|
||||
@@ -90,7 +90,7 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
def test_one_detail_page_per_record(self):
|
||||
found = [d for d in os.listdir(os.path.join(OUT, "trails"))
|
||||
if os.path.isfile(os.path.join(OUT, "trails", d, "index.html"))]
|
||||
self.assertEqual(len(self.records), 204)
|
||||
self.assertEqual(len(self.records), 196)
|
||||
self.assertEqual(sorted(found), sorted(r["id"] for r in self.records))
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, "index.html")))
|
||||
|
||||
@@ -175,8 +175,8 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
v = raw.get("verification", {})
|
||||
if raw["source"].get("line_file") and v.get("verified") and abs(v.get("difference_percent", 0)) > 15:
|
||||
expected.add(rec["id"])
|
||||
self.assertEqual(len(expected), 25)
|
||||
self.assertIn("voyageur", expected)
|
||||
self.assertEqual(len(expected), 17)
|
||||
self.assertIn("knobstone", expected)
|
||||
for rec in self.records:
|
||||
page = self.pages[rec["id"]]
|
||||
has_notice = 'class="notice notice--partial"' in page
|
||||
@@ -305,8 +305,7 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
|
||||
def test_names_marked_with_their_language(self):
|
||||
langs = site.load().name_lang
|
||||
self.assertEqual(langs, {"traversee-charlevoix": "fr", "sentier-national": "fr",
|
||||
"sentier-international-appalaches": "fr"})
|
||||
self.assertEqual(langs, {"traversee-charlevoix": "fr", "sentier-international-appalaches": "fr"})
|
||||
with open(os.path.join(OUT, "index.html"), encoding="utf-8") as f:
|
||||
home = f.read()
|
||||
by_id = {r["id"]: r for r in self.records}
|
||||
@@ -331,7 +330,7 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
self.assertIn('scope="col"', th, path)
|
||||
|
||||
def test_maplibre_is_not_loaded_with_the_page(self):
|
||||
# app.js loads MapLibre when the map scrolls into view or is touched, from the
|
||||
# app.js loads MapLibre a moment after the page has loaded, from the
|
||||
# addresses on its own tag (layout.py); the page itself names no MapLibre file.
|
||||
with open(os.path.join(OUT, "index.html"), encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
@@ -446,7 +445,7 @@ class RenderUnitTest(unittest.TestCase):
|
||||
rec = sample_record("L Trail")
|
||||
rec["hike"] = {"official_url": "https://official.example/"}
|
||||
rec["link"] = [{"title": "T", "publisher": "Wiki", "url": "https://wiki.example/t"}]
|
||||
buttons = re.search(r'<p class="cluster trail-actions">.*?</p>', trail.page_head(rec), re.S).group(0)
|
||||
buttons = re.search(r'<p class="cluster trail-actions">.*?</p>', trail.action_buttons(rec), re.S).group(0)
|
||||
self.assertIn("Official site", buttons)
|
||||
self.assertNotIn("wiki.example", buttons)
|
||||
|
||||
@@ -454,7 +453,7 @@ class RenderUnitTest(unittest.TestCase):
|
||||
rec = sample_record("L Trail")
|
||||
rec["link"] = [{"title": "T", "publisher": "Wiki Pub", "url": "https://wiki.example/t"},
|
||||
{"title": "U", "publisher": "Other", "url": "https://other.example/u"}]
|
||||
buttons = re.search(r'<p class="cluster trail-actions">.*?</p>', trail.page_head(rec), re.S).group(0)
|
||||
buttons = re.search(r'<p class="cluster trail-actions">.*?</p>', trail.action_buttons(rec), re.S).group(0)
|
||||
self.assertIn('href="https://wiki.example/t"', buttons)
|
||||
self.assertIn("Wiki Pub", buttons)
|
||||
self.assertNotIn("other.example", buttons)
|
||||
|
||||
@@ -13,10 +13,10 @@ class RecordsTest(unittest.TestCase):
|
||||
cls.recs = records.load_records()
|
||||
|
||||
def test_counts(self):
|
||||
self.assertEqual(len(self.recs), 204)
|
||||
self.assertEqual(len(self.recs), 196)
|
||||
self.assertEqual(sum(r["derived"]["kind"] == "route" for r in self.recs), 57)
|
||||
self.assertEqual(sum(r["derived"]["kind"] == "designated" for r in self.recs), 147)
|
||||
self.assertEqual(sum(r["derived"]["has_line"] for r in self.recs), 126)
|
||||
self.assertEqual(sum(r["derived"]["kind"] == "designated" for r in self.recs), 139)
|
||||
self.assertEqual(sum(r["derived"]["has_line"] for r in self.recs), 118)
|
||||
|
||||
def test_sorted_by_id(self):
|
||||
ids = [r["id"] for r in self.recs]
|
||||
|
||||
@@ -190,14 +190,14 @@ class InBrief(unittest.TestCase):
|
||||
self.assertIn("trail network", net[0])
|
||||
self.assertTrue(any(x.startswith("Most walks start at ") for x in net))
|
||||
part = self.sentences(load("allegheny-trail"))
|
||||
self.assertTrue(any("computed from the part of the track on file, about 5% of the published length" in x for x in part))
|
||||
self.assertTrue(any("computed from the part of the track on file, about 6% of the published length" in x for x in part))
|
||||
self.assertTrue(any(x == "This page has a GPX of part of the track to download." for x in part))
|
||||
|
||||
def test_trail_without_a_track_and_french_name(self):
|
||||
free = self.sentences(load("circle-of-solitude"))
|
||||
self.assertTrue(free[-1].startswith("This site has no GPX for it"))
|
||||
fr = load("sentier-national")
|
||||
self.assertTrue(self.sentences(fr)[0].startswith("Sentier National (Quebec) is a "))
|
||||
fr = load("traversee-charlevoix")
|
||||
self.assertTrue(self.sentences(fr)[0].startswith("Traversée de Charlevoix is a "))
|
||||
self.assertIn('<span lang="fr">', str(trail.brief_sentences(fr)[0]))
|
||||
|
||||
def test_a_place_name_that_starts_with_near_reads_mid_sentence(self):
|
||||
@@ -239,13 +239,28 @@ class InBrief(unittest.TestCase):
|
||||
self.assertEqual("highest point" in paragraph,
|
||||
bool(h.get("high_point") or h.get("high_point_m") or rec["derived"].get("elevation")), rec["id"])
|
||||
|
||||
def test_the_paragraph_is_in_the_page_head_before_the_buttons(self):
|
||||
def test_the_map_area_comes_first_and_the_paragraph_is_under_it(self):
|
||||
rec = load("appalachian")
|
||||
body = str(trail.render(rec, SITE, [rec])[2])
|
||||
self.assertLess(body.index('class="trail-lede"'), body.index('class="trail-brief"'))
|
||||
self.assertLess(body.index('class="trail-brief"'), body.index('class="note trail-checked"'))
|
||||
self.assertLess(body.index('class="note trail-checked"'), body.index('class="cluster trail-actions"'))
|
||||
self.assertIn("<strong>In brief.</strong>", body)
|
||||
order = ['class="titleblock', 'class="cluster trail-actions"', 'id="glance-title"', 'class="mapfig ',
|
||||
'id="brief-title"', 'class="trail-brief"', 'class="note trail-checked"']
|
||||
at = [body.index(x) for x in order]
|
||||
self.assertEqual(at, sorted(at), order)
|
||||
self.assertIn("<h2 id=\"brief-title\">In brief</h2>", body)
|
||||
self.assertIn('class="trail-summary"', body) # the summary in full stays in the page, as text
|
||||
self.assertLess(body.index('id="brief-title"'), body.index('id="morelinks-title"') if 'id="morelinks-title"' in body else len(body))
|
||||
|
||||
def test_the_lead_above_the_map_is_the_first_sentence_and_only_when_short(self):
|
||||
rec = load("appalachian")
|
||||
lead = text_of(trail.lead_text(rec))
|
||||
self.assertTrue(hike.summary(rec).startswith(lead))
|
||||
self.assertLessEqual(len(lead), trail.LEAD_MAX)
|
||||
long_rec = copy.deepcopy(rec)
|
||||
long_rec["hike"]["summary"] = "A " + "very " * 60 + "long first sentence. A second one."
|
||||
self.assertEqual(str(trail.lead_text(long_rec)), "")
|
||||
body = str(trail.render(long_rec, SITE, [long_rec])[2])
|
||||
self.assertNotIn('class="trail-lede"', body)
|
||||
self.assertIn("very very", body) # but the whole summary is under the map
|
||||
|
||||
|
||||
def words_km(rec):
|
||||
|
||||
|
Before Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 6.6 KiB |