Add saved trails, and move the units and theme switches to the header
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

A visitor can save trails with a star on every list row and a Save
button on each trail page. The list is kept in localStorage (lh-saved)
and shown at /saved/, with a map of only those trails and a link that
carries the list in its address (/saved/?t=id,id) so it can be
bookmarked or sent to another device or person. A list opened from a
link never overwrites the visitor's own; "Save these" adds to it. The
page is noindex and left out of the sitemap.

The miles/km switch and the auto/light/dark choice move from the footer
to the header on every page, beside a Saved link that shows the count.
They are hidden without JavaScript.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-15 16:01:29 -07:00
1 parent ad2223f427
commit 46dc81523c
14 files changed
+1122 -59

No files matched your search

+303 -3
View File
@@ -1,7 +1,9 @@
/* Site script, served at /assets/app.js (deferred). Vanilla JS, no build step.
1. Preferences: theme, length order and base map (saved in localStorage; applied
early by prefs.js)
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. Data is fetched 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
@@ -78,6 +80,37 @@
if (!root.dataset.theme) document.dispatchEvent(new Event('olt:theme'));
});
/* The theme menu in the header: a <details> whose button shows the theme in
use (by CSS, from html[data-theme]) and whose menu holds the three themes
as radios. A choice made with the pointer, or Enter, closes it; the arrow
keys move through the choices and leave it open. Escape, a press outside
it, or the focus leaving it closes it too. */
document.querySelectorAll('[data-theme-menu]').forEach(function (menu) {
var summary = menu.querySelector('summary');
var byPointer = false;
function close(refocus) {
if (!menu.open) return;
menu.open = false;
if (refocus) summary.focus();
}
menu.addEventListener('keydown', function (e) {
byPointer = false;
if (e.key === 'Escape' && menu.open) { e.preventDefault(); close(true); }
else if (e.key === 'Enter' && e.target.name === 'theme') { e.preventDefault(); close(true); }
});
menu.querySelector('fieldset').addEventListener('pointerdown', function () { byPointer = true; });
menu.addEventListener('change', function () {
if (byPointer) close(true);
byPointer = false;
});
menu.addEventListener('focusout', function (e) {
if (e.relatedTarget && !menu.contains(e.relatedTarget)) close(false);
});
document.addEventListener('pointerdown', function (e) {
if (menu.open && !menu.contains(e.target)) close(false);
});
});
/* A length in both units, in the reader's order: "800 mi (1,287 km)". */
function lengthText(km) {
var k = fmt.format(km) + ' km';
@@ -97,6 +130,266 @@
return getComputedStyle(probe).color;
}
/* 1b. Saved trails -----------------------------------------------------------
The visitor's saved trails: their ids in the order saved, a JSON array in
localStorage under lh-saved. Nothing leaves the browser. Every read and
write is guarded: when storage is missing, blocked or full, the list is
kept for this page only, and a note says so the first time a save cannot
be kept. Ids that match no trail are ignored; a page that lists every
trail (ol[data-every-trail]: home, /saved/) also drops them from storage.
Each [data-save] button saves or unsaves its trail (aria-pressed); each
[data-saved-count] shows how many are saved. A change made in another tab
arrives by the storage event. Every change fires olt:saved. */
var SAVED_KEY = 'lh-saved';
var ID_FORM = /^[a-z0-9][a-z0-9-]{0,99}$/;
var savedHere = null; /* the list, while storage will not keep it */
var everyTrail = null; /* id -> true, on a page that lists every trail */
(function () {
var all = document.querySelector('ol.entries[data-every-trail]');
if (!all) return;
everyTrail = {};
all.querySelectorAll('.entry[data-id]').forEach(function (li) { everyTrail[li.dataset.id] = true; });
})();
/* Well-formed ids, each once, and where the page knows every trail, only
trails that exist. */
function cleanIds(ids) {
var seen = {};
return ids.filter(function (id) {
if (typeof id !== 'string' || !ID_FORM.test(id) || seen[id]) return false;
seen[id] = true;
return !everyTrail || everyTrail[id] === true;
});
}
function storedSaved() {
var raw = null;
try { raw = localStorage.getItem(SAVED_KEY); } catch (e) { return []; }
try {
var list = JSON.parse(raw || '[]');
return Array.isArray(list) ? list : [];
} catch (e) { return []; }
}
function readSaved() {
return savedHere ? savedHere.slice() : cleanIds(storedSaved());
}
/* Store the list; false when storage will not keep it. */
function storeSaved(list) {
try {
if (list.length) localStorage.setItem(SAVED_KEY, JSON.stringify(list));
else localStorage.removeItem(SAVED_KEY);
return true;
} catch (e) { return false; }
}
/* A note at the foot of the window, once a page, when a save cannot be kept.
It is a live region from the start, so it is announced when filled. */
var savedNote = document.createElement('p');
savedNote.className = 'save-note';
savedNote.setAttribute('role', 'status');
document.body.appendChild(savedNote);
var savedNoteShown = false;
function sayNotKept() {
if (savedNoteShown) return;
savedNoteShown = true;
savedNote.textContent = 'This browser is not keeping saved trails, so they last only while this page is open.';
var clear = function () { savedNote.textContent = ''; };
savedNote.addEventListener('click', clear);
setTimeout(clear, 15000);
}
function syncSaved() {
var list = readSaved();
var on = {};
list.forEach(function (id) { on[id] = true; });
document.querySelectorAll('[data-save]').forEach(function (button) {
var saved = on[button.dataset.save] === true;
button.setAttribute('aria-pressed', saved ? 'true' : 'false');
if (button.hasAttribute('title')) button.title = saved ? 'Saved' : 'Save';
var word = button.querySelector('.save__word');
if (word) word.textContent = saved ? 'Saved' : 'Save';
});
document.querySelectorAll('[data-saved-count]').forEach(function (count) {
count.textContent = list.length ? String(list.length) : '';
count.hidden = !list.length;
});
document.dispatchEvent(new CustomEvent('olt:saved', { detail: { ids: list } }));
}
function writeSaved(list) {
list = cleanIds(list);
if (storeSaved(list)) savedHere = null;
else { savedHere = list.slice(); sayNotKept(); }
syncSaved();
return list;
}
function toggleSaved(id) {
var list = readSaved();
var i = list.indexOf(id);
if (i === -1) list.push(id); else list.splice(i, 1);
writeSaved(list);
}
/* The buttons are in the page from the start; one listener serves them all. */
document.addEventListener('click', function (e) {
var button = e.target.closest ? e.target.closest('[data-save]') : null;
if (button) toggleSaved(button.dataset.save);
});
window.addEventListener('storage', function (e) {
if (e.key !== SAVED_KEY && e.key !== null) return;
savedHere = null;
syncSaved();
});
/* Here every trail is known: forget saved ids that match none (a trail
taken off the site). Only those; the rest of the list is untouched. */
if (everyTrail && !savedHere) {
var stored = storedSaved();
var kept = cleanIds(stored);
if (kept.length !== stored.length) storeSaved(kept);
}
syncSaved();
/* 1c. The Saved page ---------------------------------------------------------
/saved/ holds every trail's row, hidden (olt/saved.py). With no t= in the
address it shows the visitor's saved trails; with t=<id>,<id>,... it shows
that list, marked as from a link, and changes nothing until "Save these".
A link that holds the visitor's own list is shown as theirs. On their own
list a trail they unsave stays in place, dimmed, so it can be saved again;
trails saved meanwhile (in another tab) are added at the end. The map
shows the trails listed; the link to the list is written out in full, to
copy by hand or with the Copy link button (section 5). Runs before the
maps start, so the map opens on the right trails. */
function initSavedPage(page) {
var title = page.querySelector('[data-saved-title]');
var lede = page.querySelector('[data-saved-lede]');
var from = page.querySelector('[data-saved-from]');
var dropNote = page.querySelector('[data-saved-dropped]');
var merged = page.querySelector('[data-saved-merged]');
var share = page.querySelector('[data-saved-share]');
var url = page.querySelector('[data-saved-url]');
var empty = document.querySelector('[data-saved-empty]');
var none = document.querySelector('[data-saved-none]');
var listBox = document.querySelector('[data-saved-list]');
var results = listBox.querySelector('.results');
var total = results.querySelector('[data-saved-total]');
var fig = listBox.querySelector('.mapfig[data-map]');
var drawable = {};
((fig && fig.dataset.drawable) || '').split(' ').forEach(function (id) { if (id) drawable[id] = true; });
var rows = {};
results.querySelectorAll('.entry[data-id]').forEach(function (li) { rows[li.dataset.id] = li; });
var params = new URLSearchParams(window.location.search);
var fromLink = params.has('t');
var linkIds = [];
var dropped = 0;
if (fromLink) {
var seen = {};
(params.get('t') || '').split(',').forEach(function (id) {
id = id.trim().toLowerCase();
if (!id || seen[id]) return;
seen[id] = true;
if (rows.hasOwnProperty(id)) linkIds.push(id); else dropped += 1;
});
var own = readSaved();
if (linkIds.length && own.length === linkIds.length &&
linkIds.every(function (id) { return own.indexOf(id) !== -1; })) fromLink = false;
}
var shown = fromLink ? linkIds.slice() : readSaved();
var mapOn = false;
function plural(n, one, many) { return n + ' ' + (n === 1 ? one : many); }
function render() {
var own = readSaved();
var ownSet = {};
own.forEach(function (id) { ownSet[id] = true; });
var view = fromLink ? (linkIds.length ? 'link' : 'none') : (shown.length ? 'own' : 'empty');
var heading = fromLink ? 'A list from a link' : 'Saved trails';
if (title.textContent !== heading) {
var cut = document.title.indexOf(' · ');
title.textContent = heading;
document.title = heading + (cut === -1 ? '' : document.title.slice(cut));
}
lede.hidden = fromLink;
from.hidden = view !== 'link';
dropNote.hidden = !dropped;
dropNote.textContent = dropped ? plural(dropped, 'trail', 'trails') + ' in the link ' +
(dropped === 1 ? 'is not on this site, so it is' : 'are not on this site, so they are') + ' left out.' : '';
empty.hidden = view !== 'empty';
none.hidden = view !== 'none';
listBox.hidden = view === 'empty' || view === 'none';
var order = {};
shown.forEach(function (id, i) { order[id] = i; });
Object.keys(rows).forEach(function (id) {
var li = rows[id];
var listed = order.hasOwnProperty(id);
li.hidden = !listed;
if (listed) li.dataset.order = String(order[id]); else delete li.dataset.order;
li.classList.toggle('is-unsaved', view === 'own' && listed && !ownSet[id]);
});
var n = fromLink ? linkIds.length : own.length;
total.innerHTML = '';
var strong = document.createElement('strong');
strong.textContent = String(n);
total.appendChild(strong);
total.appendChild(document.createTextNode(n === 1 ? ' trail' : ' trails'));
var ids = fromLink ? linkIds : own;
share.hidden = view === 'none' || !ids.length;
url.textContent = window.location.origin + '/saved/?t=' + ids.join(',');
var onMap = shown.filter(function (id) { return drawable[id]; });
if (fig) fig.hidden = !onMap.length;
return onMap;
}
var onMap = render();
var mapIds = onMap.join(' ');
/* The map starts only when it has a trail to draw. */
if (fig && onMap.length) {
fig.dataset.ids = mapIds;
mapOn = true;
} else if (fig) {
fig.removeAttribute('data-map');
}
var mergeButton = page.querySelector('[data-saved-merge]');
mergeButton.addEventListener('click', function () {
var own = readSaved();
var added = 0;
linkIds.forEach(function (id) {
if (own.indexOf(id) === -1) { own.push(id); added += 1; }
});
if (added) writeSaved(own);
merged.textContent = added ? 'Added ' + plural(added, 'trail', 'trails') + ' to your saved trails.'
: 'All of these were saved already.';
});
document.addEventListener('olt:saved', function (e) {
if (!fromLink) {
e.detail.ids.forEach(function (id) { if (shown.indexOf(id) === -1) shown.push(id); });
}
var ids = render();
if (ids.length && fig && !mapOn) { window.location.reload(); return; }
if (ids.length && ids.join(' ') !== mapIds) {
mapIds = ids.join(' ');
maps.forEach(function (m) { if (m.kind === 'overview') setVisible(m, ids); });
}
var select = results.querySelector('[data-sort-select]');
applySortUI(results, select ? select.value : 'saved', false);
});
}
var savedPage = document.querySelector('[data-saved-page]');
if (savedPage) initSavedPage(savedPage);
/* 2. Maps ------------------------------------------------------------------- */
var STYLE_URL = 'https://tiles.openfreemap.org/styles/positron';
@@ -881,6 +1174,8 @@
var COLUMN_PRIMARY = { 'name': 'name', 'length': 'length-desc', 'time': 'time-asc', 'climb': 'climb-desc' };
var COLUMN_TOGGLE = { 'name': 'name-desc', 'name-desc': 'name', 'length-desc': 'length-asc', 'length-asc': 'length-desc',
'time-asc': 'time-desc', 'time-desc': 'time-asc', 'climb-desc': 'climb-asc', 'climb-asc': 'climb-desc' };
/* The Saved page's list also has the order saved (rows numbered in data-order by section 1c). */
if (savedPage) SORT_KEYS.saved = 1;
function normalizeSortKey(value, dflt) {
if (SORT_KEYS[value]) return value;
@@ -893,6 +1188,11 @@
function compareEntries(a, b, key) {
key = normalizeSortKey(key, 'name');
var an = a.dataset.name || '', bn = b.dataset.name || '';
if (key === 'saved') {
var ao = a.dataset.order ? Number(a.dataset.order) : Infinity;
var bo = b.dataset.order ? Number(b.dataset.order) : Infinity;
return cmpNum(ao, bo) || cmpStr(an, bn);
}
if (key === 'name') return cmpStr(an, bn);
if (key === 'name-desc') return cmpStr(bn, an);
if (key === 'climb-desc' || key === 'climb-asc') {
@@ -969,7 +1269,7 @@
function replaceSortInUrl(root, key) {
var p = new URLSearchParams(window.location.search);
if (key === defaultSortOf(root)) p.delete('sort'); else p.set('sort', key);
var q = p.toString();
var q = p.toString().replace(/%2C/g, ','); /* a Saved list's t=a,b,c stays readable */
window.history.replaceState(null, '', (q ? '?' + q : window.location.pathname) + window.location.hash);
}
@@ -1299,7 +1599,7 @@
button.hidden = false;
button.addEventListener('click', function () {
var text = target.textContent.trim();
function ok() { if (done) done.textContent = 'Copied: ' + text; }
function ok() { if (done) done.textContent = button.dataset.copyDone || 'Copied: ' + text; }
function manual() {
var range = document.createRange();
range.selectNodeContents(target);
+4 -2
View File
@@ -1,6 +1,8 @@
/* Runs in <head>, before first paint: marks that JavaScript runs, and applies the
reader's saved theme, length order and base map. Saved by app.js (the footer
switches, and the Outdoor / Plain switch on a trail map). */
reader's saved theme, length order and base map. Saved by app.js (the units
switch and theme menu in the header, and the Outdoor / Plain switch on a
trail map). The theme menu's button shows the theme from html[data-theme],
so it is right from the first paint too. */
(function () {
'use strict';
var root = document.documentElement;
+267 -9
View File
@@ -8,7 +8,7 @@
Themes: `color-scheme: light dark` follows prefers-color-scheme, and every
colour token is written once with light-dark(). /assets/prefs.js pins a
theme with <html data-theme="light|dark"> and the length order with
<html data-units="km"> (the footer switches set both); miles and feet come first without it.
<html data-units="km"> (the switches in the header set both); miles and feet come first without it.
No inline styles except custom properties carrying data (--km, --n, --pos),
which the Content-Security-Policy allows through style-src-attr.
@@ -153,6 +153,8 @@ h1, h2, h3, h4 {
}
p, ul, ol, dl, figure, blockquote { margin: 0; }
/* hidden always hides, whatever display a class gives the element. */
[hidden] { display: none !important; }
p { text-wrap: pretty; }
img, svg { display: block; max-inline-size: 100%; }
@@ -219,7 +221,7 @@ code.raw {
position: absolute;
inset-block-start: var(--space-2);
inset-inline-start: var(--space-2);
z-index: 10;
z-index: 40;
padding: var(--space-2) var(--space-4);
background: var(--ink);
color: var(--paper);
@@ -228,18 +230,49 @@ code.raw {
}
.skip-link:focus { transform: none; }
/* The header. Narrow: the name and the two display switches on the first row,
the sections on a second row of their own, spread across the width like a
tab bar. From 50rem: one row, name, sections, then the switches set off by
a hairline. Above everything on the page, so the theme menu opens over it. */
.site-header {
position: relative;
z-index: 20;
background: var(--paper);
border-block-start: 4px solid var(--trail);
border-block-end: 3px double var(--rule-strong);
}
.site-header__inner {
display: flex;
flex-wrap: wrap;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
grid-template-areas: "mark prefs" "nav nav";
align-items: center;
justify-content: space-between;
gap: var(--space-2) var(--space-5);
padding-block: var(--space-3);
column-gap: var(--space-4);
padding-block-start: var(--space-2);
}
.site-header .wordmark { grid-area: mark; justify-self: start; }
.site-nav { grid-area: nav; margin-block-start: var(--space-2); border-block-start: 1px solid var(--rule); }
.site-nav .nav { justify-content: space-between; }
.prefs { grid-area: prefs; }
.site-header .wordmark { white-space: nowrap; }
/* The narrowest phones (360px and less): the name a little smaller, so it
keeps to one line beside the switches. */
@media (max-width: 23.5rem) {
.site-header__inner { column-gap: var(--space-3); }
.site-header .wordmark { gap: var(--space-2); font-size: 1.1875rem; }
.site-header .wordmark__mark { inline-size: 1.5rem; block-size: 1.5rem; }
}
/* Without JavaScript there are no switches: the name sits alone on its row. */
html:not(.js) .site-header__inner { grid-template-areas: "mark mark" "nav nav"; }
@media (min-width: 50rem) {
.site-header__inner {
grid-template-columns: auto minmax(0, 1fr) auto;
grid-template-areas: "mark nav prefs";
column-gap: var(--space-5);
padding-block: var(--space-3);
}
html:not(.js) .site-header__inner { grid-template-areas: "mark nav nav"; }
.site-nav { justify-self: end; margin-block-start: 0; border-block-start: 0; }
.prefs { padding-inline-start: var(--space-5); border-inline-start: 1px solid var(--rule); }
}
.wordmark {
@@ -272,6 +305,125 @@ body:has(.hero--home) .site-header .wordmark { visibility: hidden; }
.nav a:hover { border-block-end-color: var(--rule-strong); }
.nav a[aria-current] { border-block-end-color: var(--trail); }
/* Saved, with how many: the star turns trail red once something is saved. */
.nav__saved a { gap: 0.35rem; }
.nav__saved .star { inline-size: 1rem; block-size: 1rem; }
.nav__saved:has(.nav__count:not([hidden])) .star { color: var(--trail); }
.nav__saved:has(.nav__count:not([hidden])) .star path { fill: currentColor; }
.nav__count {
min-inline-size: 1.5em;
padding: 0 0.4em;
border-radius: 999px;
background: var(--ink);
color: var(--paper);
font: 600 var(--step--2)/1.5 var(--font-sans);
font-variant-numeric: tabular-nums;
text-align: center;
}
/* The star of a saved trail (common.ICON_STAR): an outline, filled when saved. */
.star path { fill: none; stroke: currentColor; stroke-width: 1.6; }
/* The display switches: units (a .seg) and the theme menu. 44px targets on
a narrow or touch screen; a little lower beside the links on a desktop. */
.prefs { --pref-h: 2.75rem; display: flex; align-items: center; gap: var(--space-2); }
@media (min-width: 50rem) and (pointer: fine) { .prefs { --pref-h: 2.25rem; } }
.prefs__units { min-inline-size: 0; margin: 0; padding: 0; border: 0; }
.seg--prefs { background: var(--surface); }
.seg--prefs span[aria-hidden] {
min-inline-size: 2.75rem;
min-block-size: var(--pref-h);
padding-block: 0;
font: 600 var(--step--1)/1 var(--font-sans);
letter-spacing: 0.02em;
}
.seg--prefs .vh { min-block-size: 0; padding: 0; }
.theme { position: relative; }
.theme__button {
display: flex;
align-items: center;
gap: var(--space-2);
min-inline-size: 2.75rem;
min-block-size: var(--pref-h);
padding: 0 var(--space-2) 0 var(--space-3);
border: 1px solid var(--rule-strong);
border-radius: var(--radius);
background: var(--surface);
color: var(--ink);
font: 600 var(--step--1)/1 var(--font-sans);
cursor: pointer;
list-style: none;
}
.theme__button::-webkit-details-marker { display: none; }
.theme__button::after {
content: "";
flex: none;
inline-size: 0.4rem;
block-size: 0.4rem;
border: solid currentColor;
border-width: 0 1.5px 1.5px 0;
transform: translateY(-25%) rotate(45deg);
}
.theme[open] > .theme__button::after { transform: translateY(25%) rotate(-135deg); }
.theme__button:hover { background: var(--sunken); }
.theme[open] > .theme__button { background: var(--ink); border-color: var(--ink); color: var(--paper); }
.theme[open] > .theme__button:focus-visible { outline-offset: 2px; }
/* The button shows the theme in use, from html[data-theme] (prefs.js sets it
before first paint): its icon, and its name from 50rem. */
.theme__icon, .theme__now > span { display: none; }
.theme__icon svg { inline-size: 1.25rem; block-size: 1.25rem; }
:root:not([data-theme]) .theme__icon--auto,
:root[data-theme="light"] .theme__icon--light,
:root[data-theme="dark"] .theme__icon--dark { display: block; }
:root:not([data-theme]) .theme__now--auto,
:root[data-theme="light"] .theme__now--light,
:root[data-theme="dark"] .theme__now--dark { display: inline; }
@media (max-width: 49.99rem) {
.theme__button { padding-inline: var(--space-2); }
.theme__now { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
}
@media (max-width: 23.5rem) {
.prefs { gap: 0.375rem; }
.theme__button { justify-content: center; padding-inline: 0; }
.theme__button::after { display: none; }
}
.theme__menu {
position: absolute;
inset-block-start: calc(100% + var(--space-2));
inset-inline-end: 0;
z-index: 1;
display: grid;
gap: 2px;
min-inline-size: 14rem;
margin: 0;
padding: var(--space-1);
border: 1px solid var(--ink);
background: var(--surface);
box-shadow: 4px 4px 0 var(--rule);
}
.theme__option { position: relative; display: block; }
.theme__option input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; }
.theme__choice {
display: flex;
align-items: center;
gap: var(--space-3);
min-block-size: 2.75rem;
padding: var(--space-1) var(--space-3);
color: var(--ink);
font: 500 var(--step-0)/1.2 var(--font-sans);
}
.theme__choice > svg { flex: none; inline-size: 1.25rem; block-size: 1.25rem; }
.theme__label small { display: block; color: var(--ink-2); font: 400 var(--step--1)/1.3 var(--font-sans); }
.theme__option input:hover:not(:checked) + .theme__choice { background: var(--sunken); }
.theme__option input:checked + .theme__choice { background: var(--ink); color: var(--paper); font-weight: 600; }
.theme__option input:checked + .theme__choice small { color: inherit; }
.theme__option input:focus-visible + .theme__choice { outline: 3px solid var(--focus); outline-offset: -3px; }
.theme__option input:checked:focus-visible + .theme__choice { outline-color: var(--paper); }
/* Saving needs JavaScript: without it, its controls are not offered. */
html:not(.js) .js-only { display: none !important; }
.breadcrumb ol {
display: flex;
flex-wrap: wrap;
@@ -309,8 +461,6 @@ body:has(.hero--home) .site-header .wordmark { visibility: hidden; }
.site-footer__about { grid-column: span 2; max-inline-size: 34rem; }
.site-footer .wordmark { font-size: var(--step-1); }
.site-footer__about > * + * { margin-block-start: var(--space-3); }
.site-footer__prefs { display: grid; align-content: start; gap: var(--space-4); }
.site-footer__prefs .seg { background: var(--surface); }
.site-footer__base {
padding-block: var(--space-4);
border-block-start: 1px solid var(--rule);
@@ -1015,6 +1165,39 @@ html:not(.js) .list-head__arrow { display: none; }
}
.entry[hidden] { display: none; }
.entry:hover, .entry.is-highlit { background: color-mix(in srgb, var(--highlight) 55%, transparent); }
/* The Save star of a row (common.save_button): drawn just under the logo
plate, out of the row's flow, so it never makes a row taller or moves a
column. Every layout leaves room there: the plate is the top of the first
column, which holds nothing else (its height is --plate-w at 3:2). The
button is a 44px target with the star at its centre. */
.entry { position: relative; --pad-x: var(--space-2); }
.save--row {
position: absolute;
inset-block-start: calc(var(--space-4) + var(--plate-w) * 2 / 3 - 0.375rem);
inset-inline-start: calc(var(--pad-x) + (var(--plate-w) - 2.75rem) / 2);
display: grid;
place-items: center;
inline-size: 2.75rem;
block-size: 2.75rem;
margin: 0;
padding: 0;
border: 0;
border-radius: 50%;
background: none;
color: var(--ink-3);
cursor: pointer;
}
.save--row .star { inline-size: 1.375rem; block-size: 1.375rem; }
.save--row:hover { color: var(--ink); }
.save--row:hover .star path { fill: color-mix(in srgb, var(--highlight) 70%, transparent); }
.save--row:focus-visible { outline-offset: -0.4rem; border-radius: 50%; }
.save[aria-pressed="true"] { color: var(--trail); }
.save[aria-pressed="true"] .star path,
.save--row[aria-pressed="true"]:hover .star path { fill: currentColor; }
/* On the Saved page, a trail unsaved during the visit stays, dimmed, to be saved again. */
.entry.is-unsaved > :not(.entry__body),
.entry.is-unsaved .entry__body > :not(.save) { opacity: 0.5; }
.entry__plate { grid-area: plate; align-self: start; }
.entry__body { grid-area: body; display: grid; gap: var(--space-1); align-content: start; min-inline-size: 0; }
.entry__kicker { display: flex; flex-wrap: wrap; gap: var(--space-1); }
@@ -1139,6 +1322,9 @@ html:not(.js) .list-head__arrow { display: none; }
padding-block: var(--space-4);
}
.entry__plate { aspect-ratio: 5 / 3; }
/* The tallest plate and the shortest rows: the star a little smaller and closer. */
.save--row { inset-block-start: calc(var(--space-4) + var(--plate-w) * 2 / 3 - 0.5rem); }
.save--row .star { inline-size: 1.25rem; block-size: 1.25rem; }
.entry__facts {
grid-template-columns: 9.5rem 6rem 7rem 6.5rem;
gap: var(--space-4);
@@ -1503,6 +1689,10 @@ td .linklist a { font-weight: 400; }
@media (forced-colors: active) {
.swatch, .ratio > span, .loglen::after, .gauge__mark { forced-color-adjust: none; }
.tag--nst, .seg input:checked + span { forced-color-adjust: auto; border: 1px solid CanvasText; }
/* The theme in use is marked by more than its ground: a frame, and a check. */
.theme__option input:checked + .theme__choice { border: 1px solid CanvasText; }
.theme__option input:checked + .theme__choice .theme__label::after { content: " \2713"; }
.nav__count { border: 1px solid CanvasText; }
}
/* 10. Added pages: regions, routes, sources, logos, about, data ----------- */
@@ -1885,6 +2075,7 @@ a.tag:hover { background: var(--sunken); }
.key { display: none; }
.entry {
--plate-w: 3.75rem;
--pad-x: 0px;
grid-template-areas: "plate body" ". facts" ". note";
gap: var(--space-2) var(--space-3);
padding: var(--space-4) 0;
@@ -1937,3 +2128,70 @@ a.tag:hover { background: var(--sunken); }
.morelinks__by { color: var(--ink-2); }
.morelinks small { display: block; color: var(--ink-2); font-size: var(--step--1); line-height: 1.4; }
.morelinks svg { display: inline; inline-size: 0.85em; block-size: 0.85em; vertical-align: -0.1em; }
/* 13. Saved trails: the Save button of a trail page, the Saved page ---------- */
.save--page[aria-pressed="true"] { border-color: var(--trail); }
.saved-head .notice { max-inline-size: 46rem; margin-block-start: var(--space-2); }
html.js .saved-nojs { display: none; }
html:not(.js) .saved-body { display: none; }
.saved-from { border-inline-start-color: var(--route); background: var(--highlight); }
.saved-from .cluster { margin-block-start: var(--space-1); }
.saved-status { color: var(--green); font: 500 var(--step--1)/1.4 var(--font-sans); }
.saved-status:empty { display: none; }
.saved-body { padding-block-start: var(--space-5); }
.saved-list { display: grid; gap: var(--space-5); }
.saved-empty .star { display: inline-block; inline-size: 1.15em; block-size: 1.15em; vertical-align: -0.2em; color: var(--ink-2); }
.saved-empty .button { margin-block-start: var(--space-2); }
/* The link to a list: written out in full (it can be selected with one tap
and copied by hand), with a Copy link button beside it. */
.share {
display: grid;
gap: var(--space-2);
max-inline-size: 46rem;
margin-block-start: var(--space-4);
padding: var(--space-3) var(--space-4) var(--space-4);
border: 1px solid var(--rule-strong);
background: var(--surface);
font-family: var(--font-sans);
}
.share__title { color: var(--ink); font: 600 var(--step--2)/1.4 var(--font-sans); letter-spacing: 0.08em; text-transform: uppercase; }
.share__what { color: var(--ink-2); font: 400 var(--step--1)/1.45 var(--font-sans); }
.share__row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-3); }
.share__url {
flex: 1 1 16rem;
min-inline-size: 0;
padding: var(--space-2) var(--space-3);
border: 1px solid var(--rule-strong);
border-radius: var(--radius);
background: var(--paper);
color: var(--ink);
font-size: var(--step--1);
line-height: 1.45;
overflow-wrap: anywhere;
-webkit-user-select: all;
user-select: all;
}
.share__done { color: var(--green); font: 500 var(--step--1)/1.4 var(--font-sans); }
.share__done:empty { display: none; }
/* Said once, at the foot of the window, when the browser will not keep a
save. A live region from the start: empty, it takes no room. */
.save-note {
position: fixed;
z-index: 50;
inset-inline: var(--space-4);
inset-block-end: var(--space-4);
max-inline-size: 32rem;
margin-inline: auto;
padding: var(--space-3) var(--space-4);
border: 1px solid var(--ink);
background: var(--surface);
color: var(--ink);
box-shadow: 4px 4px 0 var(--rule);
font: 500 var(--step--1)/1.45 var(--font-sans);
cursor: pointer;
}
.save-note:empty { padding: 0; border: 0; box-shadow: none; pointer-events: none; }
+39
View File
@@ -207,6 +207,25 @@ FOOTER_MAP_CREDIT = Markup(
"the U.S. Geological Survey, NOAA, ArcticDEM and INEGI; Canada terrain data under the Open Government "
"Licence - Canada. The full credit is under each trail map.")
def save_button(rec, *, row=True):
"""The control that saves a trail to the visitor's saved trails, or takes it off.
A real <button>, never inside a link, named for the trail ("Save Pacific
Crest Trail") whatever its state; app.js sets aria-pressed (and the word
"Save" or "Saved" on a trail page) from the saved list, lh-saved in
localStorage. row: the star alone, placed under the logo of a list row
(style.css .save--row); otherwise the button beside a trail page's actions.
Hidden without JavaScript, which saving needs (.js-only).
"""
tid = esc(rec["id"])
label = f'<span class="vh">Save {name(rec)}</span>'
if row:
return Markup(f'<button class="save save--row js-only" type="button" data-save="{tid}" '
f'aria-pressed="false" title="Save">{ICON_STAR}{label}</button>')
return Markup(f'<button class="button button--quiet save save--page js-only" type="button" data-save="{tid}" '
f'aria-pressed="false">{ICON_STAR}<span class="save__word" aria-hidden="true">Save</span>{label}</button>')
SWATCH_LINE = Markup('<span class="swatch swatch--line" aria-hidden="true"></span>')
SWATCH_ROUTE = Markup('<span class="swatch swatch--route" aria-hidden="true"></span>')
SWATCH_ALT = Markup('<span class="swatch swatch--alt" aria-hidden="true"></span>')
@@ -218,3 +237,23 @@ ICON_DOWNLOAD = Markup('<svg viewBox="0 0 16 16" aria-hidden="true" focusable="f
'<path d="M8 1.5v9M4 7l4 4 4-4M2.5 14.5h11" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>')
ICON_EXTERNAL = Markup('<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">'
'<path d="M6 3H3v10h10v-3M9 2.5h4.5V7M13.5 2.5 7 9" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>')
# The mark of a saved trail. Its fill is set by style.css (outline when not
# saved, filled when saved), so one drawing serves every state.
ICON_STAR = Markup('<svg class="star" viewBox="0 0 24 24" aria-hidden="true" focusable="false">'
'<path d="M12 2.8l2.85 5.78 6.38.93-4.62 4.5 1.09 6.35L12 17.36l-5.7 3 1.09-6.35-4.62-4.5 '
'6.38-.93z" stroke-linejoin="round"/></svg>')
# The three themes, for the theme menu in the header: auto (half dark, as the
# device decides), light (a sun) and dark (a moon).
ICON_THEME = {
"auto": Markup('<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">'
'<circle cx="12" cy="12" r="8.25" fill="none" stroke="currentColor" stroke-width="1.7"/>'
'<path d="M12 3.75a8.25 8.25 0 0 1 0 16.5z" fill="currentColor"/></svg>'),
"light": Markup('<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">'
'<circle cx="12" cy="12" r="4.25" fill="none" stroke="currentColor" stroke-width="1.7"/>'
'<path d="M12 2.5v2.75M12 18.75v2.75M2.5 12h2.75M18.75 12h2.75M5.28 5.28l1.95 1.95'
'M16.77 16.77l1.95 1.95M5.28 18.72l1.95-1.95M16.77 7.23l1.95-1.95" fill="none" '
'stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>'),
"dark": Markup('<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">'
'<path d="M19.75 14.6A8 8 0 0 1 9.4 4.25a8.25 8.25 0 1 0 10.35 10.35z" fill="none" '
'stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/></svg>'),
}
+55 -13
View File
@@ -121,12 +121,17 @@ def gpx_cell(rec):
return f'<span class="line__status">{common.SWATCH_NONE}{esc(facets.GPX_SHORT[status])}</span>'
def entry(rec, *, level=3, extra="", routes_list=False):
def entry(rec, *, level=3, extra="", routes_list=False, hidden=False):
"""One trail in a list. Its data-* attributes drive the filters in app.js.
level: the heading level of the trail's name. extra: HTML placed last in the row.
routes_list: the Routes list, whose "By <author>" headings already say what the
row's Route badge and "Route by" line would repeat; both are left out there.
hidden: written hidden, for app.js to show (the Saved page).
The Save star follows the name in the markup (so it is the next stop for the
keyboard) but is drawn under the logo, out of the row's flow (style.css
.save--row): it never makes a row taller or moves its columns.
"""
route = facets.kind(rec) == "route"
lo, hi, est = facets.time_days(rec)
@@ -157,10 +162,13 @@ def entry(rec, *, level=3, extra="", routes_list=False):
time_html = esc(facets.time_text(rec)) + (' <small class="entry__est">estimate</small>' if est else "")
climb_html = (f'\n <div class="entry__climb"><dt>Climb</dt><dd>{words.elevation(climb_m, "stack")}'
f'<small class="entry__est">computed</small></dd></div>') if climb_m is not None else ""
if hidden:
attrs += " hidden"
return f"""<li class="entry"{attrs}>
{common.plate(rec)}
<div class="entry__body">{kicker}
<{h} class="entry__name"><a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a>{abbr_html}</{h}>{by}{desc_html}
<{h} class="entry__name"><a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a>{abbr_html}</{h}>
{common.save_button(rec)}{by}{desc_html}
<p class="entry__where">{where_html(rec)}</p>
</div>
<dl class="entry__facts">
@@ -371,14 +379,25 @@ UNITS_TOGGLE = """<fieldset class="results-units">
</div>
</fieldset>"""
def sort_select(default_sort="name"):
# The order a saved list was made in: offered first on the Saved page only,
# where app.js numbers the rows (data-order) in the order they were saved.
SAVED_ORDER = ("saved", "Order saved")
def sort_select(default_sort="name", saved=False):
"""The one sort control of every list of trails, with the page's
default order selected. Hidden without JavaScript (style.css):
it cannot work then, and the HTML is already in the default order."""
default_sort = facets.normalize_sort(default_sort)
it cannot work then, and the HTML is already in the default order.
saved: the Saved page's list, which opens in the order saved."""
sorts = facets.SORTS
if saved:
sorts = (SAVED_ORDER,) + tuple(sorts)
default_sort = SAVED_ORDER[0]
else:
default_sort = facets.normalize_sort(default_sort)
options = "".join(
f'\n <option value="{esc(k)}"{" selected" if k == default_sort else ""}>{esc(label)}</option>'
for k, label in facets.SORTS)
for k, label in sorts)
return f"""<label class="results-sort"><span class="results-sort__label">Sort by</span>
<select class="select" id="sort" name="sort" data-sort-select>{options}
</select>
@@ -398,7 +417,7 @@ def key(official=True):
</ul>"""
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name"):
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name", saved=False):
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
Every list carries the same "Sort by" control. The rows are written in
@@ -410,6 +429,13 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
sorting is within each group and the groups keep their order.
extra_fn(rec) gives HTML placed last in each row.
routes_list: passed to entry() for the Routes list (see there).
saved: the Saved page's list. Every trail's row is written hidden, and
app.js shows the saved ones (or a link's) and writes the count; the sort
control opens on the order saved.
A list that holds every trail (the finder's, the Saved page's) is marked
data-every-trail: there app.js knows every trail id, and drops the saved
ids that match no trail.
"""
default_sort = facets.normalize_sort(default_sort)
if groups is None:
@@ -421,14 +447,15 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
only_routes = bool(shown) and all(facets.kind(r) == "route" for r in shown)
noun = ("route" if only_routes else "trail") + ("" if total == 1 else "s")
lists = ""
every = ' data-every-trail' if finder or saved else ""
for heading, items, extra_fn in groups:
level = 4 if heading else 3
rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "",
routes_list=routes_list) for r in items)
routes_list=routes_list, hidden=saved) for r in items)
if heading:
lists += f'\n <h3 class="results__group">{heading}</h3>'
list_id = ' id="entries"' if finder else ""
lists += f'\n <ol class="entries"{list_id}>\n{rows}\n </ol>'
lists += f'\n <ol class="entries"{list_id}{every}>\n{rows}\n </ol>'
if finder:
count = (f'<p class="results-count" id="results-count" role="status">'
f'<strong>{total}</strong> of {total} {noun}</p>')
@@ -437,11 +464,15 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
<p><strong>No trails match these filters.</strong></p>
<button class="button button--quiet" type="button" data-reset>Clear search and filters</button>
</div>"""
elif saved:
count = '<p class="results-count" data-saved-total><strong>0</strong> trails</p>'
empty = ""
else:
count = f'<p class="results-count"><strong>{total}</strong> {noun}</p>'
empty = ""
tools = sort_select(default_sort) + "\n " + UNITS_TOGGLE
return Markup(f"""<div class="results" data-sortable data-default-sort="{esc(default_sort)}">
tools = sort_select(default_sort, saved=saved) + "\n " + UNITS_TOGGLE
dflt = SAVED_ORDER[0] if saved else default_sort
return Markup(f"""<div class="results" data-sortable data-default-sort="{esc(dflt)}">
<div class="results-head">
{count}
<div class="results-tools">
@@ -473,9 +504,15 @@ def drawable_ids(recs):
return [r["id"] for r in recs if r["id"] in tracks or hike.sketch_points(r)]
def overview_map(recs, label, *, wide=False, scope=""):
def overview_map(recs, label, *, wide=False, scope="", saved=False):
"""The map of the given trails (the overview geometry, limited to their ids
unless every trail is shown). A note instead when too little can be drawn."""
unless every trail is shown). A note instead when too little can be drawn.
saved: the Saved page's map. It is given every trail (scope "all") and
app.js limits it to the trails shown; the figure lists the ids it can draw
(data-drawable), so app.js leaves the map out when it would be empty, and
its caption counts nothing, since the list is the visitor's.
"""
ids = drawable_ids(recs)
if not ids:
return Markup('<p class="note">None of these trails has a GPX here or a known start or end, '
@@ -511,6 +548,11 @@ def overview_map(recs, label, *, wide=False, scope=""):
f'{"are" if s != 1 else "is"} shown as a dotted straight line between '
'their start and end, or a ring where only one end is known. '
'That is not the trail&rsquo;s path.')
if saved:
sentences = ["Tracks are simplified for display. Select one for its name.",
"A trail with no GPX here is shown by its start and end only: dots straight from one "
"to the other, or a ring where only one end is known."]
ids_attr += f' data-drawable="{esc(" ".join(ids))}"'
sentences.append("Each trail&rsquo;s page names its source, credit and licence. "
"Base map: OpenFreeMap, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;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)}>
+60 -20
View File
@@ -54,15 +54,64 @@ def _current(path, href):
return href != "/" and path.startswith(href)
SAVED_PATH = "/saved/"
THEMES = (("auto", "Auto"), ("light", "Light"), ("dark", "Dark"))
def prefs():
"""The reader's two display choices, at the right of the header on every page.
Units: a two-way switch, mi or km first (radios named "units", as every
units switch on the site; app.js keeps them in step and fires olt:units).
Theme: a small menu built from <details>, its button showing the theme in
use (its icon, and its name where there is room); the menu holds the three
themes as radios named "theme" (app.js fires olt:theme). The icon and name
in the button follow <html data-theme>, which prefs.js sets before first
paint, so the button is right from the start. Both need JavaScript and are
hidden without it (.js-only).
"""
icons = "".join(f'<span class="theme__icon theme__icon--{k}">{common.ICON_THEME[k]}</span>' for k, _ in THEMES)
now = "".join(f'<span class="theme__now--{k}">{label}</span>' for k, label in THEMES)
hint = {"auto": '<span class="vh">, </span><small>As your device is set</small>'}
options = "".join(
f'<label class="theme__option"><input type="radio" name="theme" value="{k}"{" checked" if k == "auto" else ""}>'
f'<span class="theme__choice">{common.ICON_THEME[k]}<span class="theme__label">{label}{hint.get(k, "")}'
f'</span></span></label>'
for k, label in THEMES)
return Markup(f"""<div class="prefs js-only">
<fieldset class="prefs__units">
<legend class="vh">Units</legend>
<div class="seg seg--prefs">
<label><input type="radio" name="units" value="mi" checked><span aria-hidden="true">mi</span><span class="vh">Miles and feet</span></label>
<label><input type="radio" name="units" value="km"><span aria-hidden="true">km</span><span class="vh">Kilometres and metres</span></label>
</div>
</fieldset>
<details class="theme" data-theme-menu>
<summary class="theme__button">{icons}<span class="vh">Theme: </span><span class="theme__now">{now}</span></summary>
<fieldset class="theme__menu">
<legend class="vh">Theme</legend>
{options}
</fieldset>
</details>
</div>""")
def header(path, site):
items = "".join(
f'<li><a href="{esc(href)}"{attrs(aria_current="page" if path == href else ("true" if _current(path, href) else None))}>'
f"{esc(text)}</a></li>"
for text, href in NAV)
# The visitor's saved trails: app.js fills in the count. Saving needs
# JavaScript, so without it the link is not offered.
items += (f'<li class="nav__saved js-only"><a href="{SAVED_PATH}"'
f'{attrs(aria_current="page" if path == SAVED_PATH else None)}>{common.ICON_STAR}Saved'
f'<span class="nav__count" data-saved-count hidden></span></a></li>')
return Markup(f"""<header class="site-header">
<div class="container site-header__inner">
<a class="wordmark" href="/"><img class="wordmark__mark" src="/assets/favicon.svg" alt="" width="28" height="28">{esc(site.name)}</a>
<nav aria-label="Main"><ul class="nav">{items}</ul></nav>
<nav class="site-nav" aria-label="Main"><ul class="nav">{items}</ul></nav>
{prefs()}
</div>
</header>""")
@@ -87,6 +136,7 @@ def footer(site):
<li><a href="/regions/">Places</a></li>
<li><a href="/lists/">Lists</a></li>
<li><a href="/routes/">Routes</a></li>
<li class="js-only"><a href="{SAVED_PATH}">Saved trails</a></li>
</ul>
</nav>
<nav aria-labelledby="footer-project">
@@ -99,23 +149,6 @@ def footer(site):
{report}
</ul>
</nav>
<div class="site-footer__prefs">
<fieldset class="field">
<legend>Theme</legend>
<div class="seg">
<label><input type="radio" name="theme" value="auto" checked><span>Auto</span></label>
<label><input type="radio" name="theme" value="light"><span>Light</span></label>
<label><input type="radio" name="theme" value="dark"><span>Dark</span></label>
</div>
</fieldset>
<fieldset class="field">
<legend>Units</legend>
<div class="seg">
<label><input type="radio" name="units" value="mi" checked><span>mi and ft first</span></label>
<label><input type="radio" name="units" value="km"><span>km and m first</span></label>
</div>
</fieldset>
</div>
</div>
<div class="site-footer__base">
<div class="container">{common.FOOTER_MAP_CREDIT}</div>
@@ -130,7 +163,7 @@ def _ld_json_block(obj):
def layout(title, body, *, path, description="", maps=False, outdoor=False, scripts=(), data=None, site=None,
jsonld=None, og_type="website"):
jsonld=None, og_type="website", noindex=False):
"""Return a complete HTML document.
title the page's own title ("Arizona National Scenic Trail"); the site
@@ -144,17 +177,23 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
scripts extra same-origin script URLs, loaded with defer after app.js.
data optional object, embedded as <script type="application/json" id="page-data">.
site settings (olt.site.Site); defaults to web/site.toml.
noindex True for a page whose content is the visitor's own (/saved/):
search engines are asked not to index it, and it has no
canonical address (its address carries the list). seo.py
leaves it out of the sitemap.
"""
site = site or site_settings.load()
full_title = f"{title} · {site.name}" if title else f"{site.name}: {site.tagline}"
description = description or site.tagline
canonical = site.canonical(path)
canonical = "" if noindex else site.canonical(path)
head = [
'<meta charset="utf-8">',
'<meta name="viewport" content="width=device-width, initial-scale=1">',
f"<title>{esc(full_title)}</title>",
f'<meta name="description" content="{esc(description)}">',
]
if noindex:
head.append('<meta name="robots" content="noindex">')
if canonical:
head.append(f'<link rel="canonical" href="{esc(canonical)}">')
head += [
@@ -168,6 +207,7 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
]
if canonical:
head.append(f'<meta property="og:url" content="{esc(canonical)}">')
if site.base_url:
# A PNG: link previews (Reddit, Slack, iMessage) do not draw an SVG.
image = esc(site.canonical("/assets/og.png"))
head.append(f'<meta property="og:image" content="{image}">')
+7 -1
View File
@@ -11,6 +11,7 @@ writes:
/regions/, /regions/<slug>/ Places: the hub and one page per state or province
/lists/, /lists/<key>/ the lists shown today (olt/browse.py); /routes/ is the Routes list
/about/ and the pages under it: /data/, /data/schema/, /data/changelog/, /sources/, /logos/
/saved/ the visitor's saved trails (olt/saved.py; not indexed)
/404.html not found
Adding a page elsewhere (regions, sources, ...): build its body as HTML,
@@ -21,7 +22,7 @@ import json
import os
import shutil
from . import browse, docs, home, layout, regions, seo, site as site_settings, thumbs, trail
from . import browse, docs, home, layout, regions, saved, seo, site as site_settings, thumbs, trail
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ASSETS_DIR = os.path.join(WEB_DIR, "assets")
@@ -132,6 +133,11 @@ def render_site(records, out_dir, repo_root, site=None):
add("/data/schema/", t, d, b)
t, d, b = docs.changelog_page(site, repo_root)
add("/data/changelog/", t, d, b)
# The visitor's own list: not indexed, and left out of the sitemap below.
t, d, b = saved.saved_page(records, site)
layout.write_page(out_dir, saved.PATH, layout.layout(
t, b, path=saved.PATH, description=d, maps=True, site=site, noindex=True))
pages += 1
docs.copy_licences(out_dir, repo_root)
seo.write_seo_files(out_dir, seo.all_paths(records, region_paths + ["/lists/"] + list_paths), site)
print(f"pages written {pages}: {len(records)} trail pages, home, 404, places, lists, about")
+78
View File
@@ -0,0 +1,78 @@
"""The Saved page, /saved/: the visitor's saved trails, or a list opened from a link.
Saved trails are kept in the visitor's browser only: localStorage, key
lh-saved, the trail ids in the order saved (app.js). A link carries a list in
its own address, /saved/?t=<id>,<id>,..., so it opens the same list on any
device, in any browser, with nothing remembered.
The page is written like every other, so it cannot know the list. It holds
every trail's row, hidden (the same rows as the catalogue, about as heavy as
the home page's list; the hidden rows' logos are not fetched), and app.js
(initSavedPage) shows the right ones:
own list no t= in the address: the visitor's saved trails, the map
of them, and the link to them with a Copy link button
nothing saved no t=, nothing saved: how to save a trail, and a link to the trails
from a link t= in the address: that list, marked as from a link, with
"Save these" (adds it to the visitor's own) and a way to
their own list; ids that match no trail are dropped and
counted. A link holding the visitor's own list is shown as theirs.
Without JavaScript the page says that saved trails need it. It is not
indexed (layout noindex) and not in the sitemap (seo.all_paths).
"""
from . import common, home
from .markup import Markup
PATH = "/saved/"
TITLE = "Saved trails"
DESCRIPTION = "The trails you saved, kept in this browser, and a link that opens the same list anywhere."
def saved_page(records, site):
"""(title, description, body) for /saved/."""
recs = sorted(records, key=home.sort_name)
star = common.ICON_STAR
body = f"""<div class="page-head saved-head" data-saved-page>
<div class="container">
<header class="titleblock"><div class="titleblock__text">
<h1 data-saved-title>{TITLE}</h1>
<p class="page-head__lede" data-saved-lede>Trails you save are kept here, in this browser on this device.</p>
</div></header>
<div class="notice saved-nojs"><p>Saved trails need JavaScript, which is off or blocked in this browser. <a href="/">See every trail</a>.</p></div>
<div class="notice saved-from" data-saved-from hidden>
<p><strong>This list came from a link.</strong> Opening it has not changed your own saved trails.</p>
<p data-saved-dropped hidden></p>
<p class="cluster">
<button class="button button--primary" type="button" data-saved-merge>{star}Save these</button>
<a class="button button--quiet" href="{PATH}">Your saved trails</a>
</p>
<p class="saved-status" data-saved-merged role="status"></p>
</div>
<section class="share" data-saved-share hidden aria-labelledby="share-title">
<h2 class="share__title" id="share-title">Link to this list</h2>
<p class="share__what">Bookmark it, or send it to another device or another person: it opens this same list in any browser.</p>
<div class="share__row">
<code class="share__url" id="saved-url" data-saved-url></code>
<button class="button button--quiet" type="button" data-copy="#saved-url" data-copy-status="#saved-copied" data-copy-done="Link copied." hidden>Copy link</button>
</div>
<p class="share__done" id="saved-copied" role="status"></p>
</section>
</div>
</div>
<div class="container section saved-body">
<div class="empty-state saved-empty" data-saved-empty hidden>
<p><strong>Nothing saved yet.</strong></p>
<p>To save a trail, select the {star}<span class="vh">star</span> in its row in any list of trails, or Save on the trail&rsquo;s page.</p>
<p><a class="button button--primary" href="/">Find a trail</a></p>
</div>
<div class="empty-state saved-empty" data-saved-none hidden>
<p><strong>None of the trails in this link are on this site.</strong></p>
<p><a href="/">See every trail</a>, or <a href="{PATH}">your saved trails</a>.</p>
</div>
<div class="saved-list" data-saved-list hidden>
{home.overview_map(recs, "Map of the trails in this list", wide=True, scope="all", saved=True)}
{home.results(recs, saved=True)}
</div>
</div>"""
return TITLE, DESCRIPTION, Markup(body)
+1
View File
@@ -181,6 +181,7 @@ def page_head(rec):
actions.append(f'<a class="button button--primary" href="#download">{common.ICON_DOWNLOAD}Download the GPX</a>')
else:
actions.append(f'<a class="button button--quiet" href="#track">GPX: {esc(facets.GPX_STATUS[facets.gpx(rec)])}</a>')
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)
+1 -1
View File
@@ -186,7 +186,7 @@ class ExtraPagesTest(unittest.TestCase):
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">'))
self.assertLess(main.index('data-map="overview"'), main.index('<ol class="entries" id="entries"'))
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"'))]
+4 -3
View File
@@ -271,10 +271,11 @@ class BuiltVocabularyTest(unittest.TestCase):
self.maxDiff = None
self.assertEqual(bad[:40], [])
def test_navigation_has_three_items(self):
def test_navigation_has_three_sections_and_saved(self):
doc = self.read("index.html")
nav = re.search(r'<nav aria-label="Main"><ul class="nav">(.*?)</ul></nav>', doc).group(1)
self.assertEqual(re.findall(r">([^<]+)</a>", nav), ["Trails", "Places", "About"])
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.assertIn('<li class="nav__saved js-only"><a href="/saved/">', nav)
def test_one_count_noun(self):
doc = self.read("index.html")
+2 -2
View File
@@ -549,8 +549,8 @@ class RenderUnitTest(unittest.TestCase):
rec = sample_record(name="A & B")
n = pages.render_site([rec], out, repo, site=site.Site("N", "T"))
# trail page + home + 404 + places hub + 1 place + lists hub + routes,
# sources, logos, about, data, schema, changelog (no list holds MIN_SIZE trails)
self.assertEqual(n, 13)
# sources, logos, about, data, schema, changelog, saved (no list holds MIN_SIZE trails)
self.assertEqual(n, 14)
with open(os.path.join(out, "trails", "x", "index.html"), encoding="utf-8") as f:
self.assertIn("A &amp; B", f.read())
with open(os.path.join(out, "index.html"), encoding="utf-8") as f:
+295
View File
@@ -0,0 +1,295 @@
"""Saved trails and the display switches in the header: what the generator writes.
The header carries the units switch and the theme menu on every page (and the
footer no longer does); every row of every list of trails, and every trail
page, has a Save button; /saved/ holds every row for app.js to show, is not
indexed and is not in the sitemap; nothing is inline. The behaviour itself
(localStorage, the link, the menu) is in app.js and was checked in browsers.
"""
import html
import os
import re
import subprocess
import sys
import unittest
from html.parser import HTMLParser
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
from olt import common, home, layout, records, saved, seo, site # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
def setUpModule():
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
def read_out(relpath):
with open(os.path.join(OUT, *relpath.split("/")), encoding="utf-8") as f:
return f.read()
def html_files():
for base, _, names in os.walk(OUT):
for n in names:
if n.endswith(".html"):
yield os.path.relpath(os.path.join(base, n), OUT).replace(os.sep, "/")
class Tree(HTMLParser):
"""Start tags with their attributes and the open elements above each one,
and the text inside each <button>."""
VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr",
"path", "circle"}
def __init__(self):
super().__init__(convert_charrefs=True)
self.stack = []
self.tags = [] # (tag, attrs, [ancestor tags])
self.buttons = [] # (attrs, text, [ancestor tags])
self._button = None
def handle_starttag(self, tag, attrs):
a = dict(attrs)
self.tags.append((tag, a, [t for t, _ in self.stack]))
if tag == "button":
self._button = [a, "", [t for t, _ in self.stack]]
if tag not in self.VOID:
self.stack.append((tag, a))
def handle_startendtag(self, tag, attrs):
self.tags.append((tag, dict(attrs), [t for t, _ in self.stack]))
def handle_endtag(self, tag):
if tag == "button" and self._button:
self.buttons.append(tuple(self._button))
self._button = None
for i in range(len(self.stack) - 1, -1, -1):
if self.stack[i][0] == tag:
del self.stack[i:]
break
def handle_data(self, data):
if self._button is not None:
self._button[1] += data
def tree(doc):
t = Tree()
t.feed(doc)
return t
class HeaderOnEveryPageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.files = sorted(html_files())
def test_every_page_has_the_switches_and_the_saved_link_in_its_header(self):
self.assertGreater(len(self.files), 250)
for rel in self.files:
doc = read_out(rel)
head = doc[doc.index('<header class="site-header">'):doc.index("</header>", doc.index('<header class="site-header">'))]
self.assertIn('<div class="prefs js-only">', head, rel)
self.assertIn('<input type="radio" name="units" value="mi" checked>', head, rel)
self.assertIn('<input type="radio" name="units" value="km">', head, rel)
self.assertIn('<details class="theme" data-theme-menu>', head, rel)
for value in ("auto", "light", "dark"):
self.assertIn(f'name="theme" value="{value}"', head, rel)
self.assertIn('<li class="nav__saved js-only"><a href="/saved/"', head, rel)
self.assertIn("data-saved-count hidden", head, rel)
def test_the_footer_no_longer_has_the_switches(self):
for rel in ("index.html", "about/index.html", "trails/pacific-crest/index.html"):
doc = read_out(rel)
foot = doc[doc.index('<footer class="site-footer">'):]
self.assertNotIn('name="theme"', foot, rel)
self.assertNotIn('name="units"', foot, rel)
self.assertIn('<li class="js-only"><a href="/saved/">Saved trails</a></li>', foot, rel)
def test_one_set_of_theme_radios_per_page(self):
# Radios named "theme" form one group per page: only the header's.
for rel in ("index.html", "saved/index.html", "trails/arizona/index.html"):
self.assertEqual(read_out(rel).count('name="theme"'), 3, rel)
def test_the_saved_link_is_current_on_the_saved_page_only(self):
self.assertIn('<a href="/saved/" aria-current="page">', read_out("saved/index.html"))
self.assertNotIn('<a href="/saved/" aria-current', read_out("index.html"))
def test_nothing_inline(self):
# The security policy allows no inline script, no <style> element and no
# event-handler attribute; the switches and the Save buttons add none.
for rel in self.files:
doc = read_out(rel)
self.assertNotIn("<style", doc, rel)
for tag, a, _ in tree(doc).tags:
self.assertFalse([k for k in a if k.startswith("on")], f"{tag} in {rel}")
if tag == "script":
self.assertTrue(a.get("src") or a.get("type") in ("application/json", "application/ld+json"), rel)
def test_the_switches_name_what_they_do(self):
prefs = layout.prefs()
self.assertIn('<legend class="vh">Units</legend>', prefs)
self.assertIn('<span class="vh">Miles and feet</span>', prefs)
self.assertIn('<span class="vh">Kilometres and metres</span>', prefs)
self.assertIn('<span class="vh">Theme: </span>', prefs)
self.assertIn('<legend class="vh">Theme</legend>', prefs)
self.assertIn('value="auto" checked', prefs)
# Each icon is drawn inline, hidden from assistive technology.
self.assertEqual(prefs.count("<svg"), 6)
self.assertEqual(prefs.count('aria-hidden="true" focusable="false"'), 6)
class SaveButtonsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.records = records.load_records(ROOT)
cls.names = {r["id"]: r["name"] for r in cls.records}
def row_buttons(self, rel):
return [(a, text, up) for a, text, up in tree(read_out(rel)).buttons if "save--row" in a.get("class", "")]
def test_every_row_of_every_list_has_a_save_button(self):
lists = ["index.html", "routes/index.html", "saved/index.html"]
lists += [f"lists/{d}/index.html" for d in os.listdir(os.path.join(OUT, "lists"))
if os.path.isfile(os.path.join(OUT, "lists", d, "index.html"))]
lists += [f"regions/{d}/index.html" for d in os.listdir(os.path.join(OUT, "regions"))
if os.path.isfile(os.path.join(OUT, "regions", d, "index.html"))]
for rel in lists:
doc = read_out(rel)
rows = re.findall(r'<li class="entry" data-id="([^"]+)"', doc)
buttons = self.row_buttons(rel)
self.assertEqual([a["data-save"] for a, _, _ in buttons], rows, rel)
for a, text, up in buttons:
self.assertEqual(a["type"], "button", rel)
self.assertEqual(a["aria-pressed"], "false", rel)
self.assertNotIn("a", up, f"a Save button inside a link in {rel}")
self.assertEqual(" ".join(text.split()), f"Save {self.names[a['data-save']]}", rel)
def test_every_trail_page_has_a_save_button_by_its_actions(self):
for rec in self.records:
doc = read_out(f"trails/{rec['id']}/index.html")
actions = doc[doc.index('<p class="cluster trail-actions">'):doc.index("</p>", doc.index('<p class="cluster trail-actions">'))]
m = re.search(r'<button class="button button--quiet save save--page js-only" type="button" '
r'data-save="([^"]+)" aria-pressed="false">', actions)
self.assertTrue(m, rec["id"])
self.assertEqual(m.group(1), rec["id"])
button = actions[m.start():actions.index("</button>", m.start())]
visible = re.search(r'<span class="save__word" aria-hidden="true">([^<]*)</span>', button).group(1)
name = html.unescape(re.sub(r"<[^>]+>", "", button[button.index('<span class="vh">'):]))
self.assertEqual((visible, name), ("Save", f"Save {rec['name']}"), rec["id"])
def test_the_star_follows_the_name_and_is_not_inside_its_link(self):
rec = self.records[0]
row = home.entry(rec)
name_link_end = row.index("</a>", row.index('class="entry__name"'))
self.assertLess(name_link_end, row.index('class="save save--row'))
self.assertLess(row.index('class="save save--row'), row.index('class="entry__where"'))
def test_names_are_escaped(self):
rec = dict(self.records[0], id="x", name='A & B <i>')
button = common.save_button(rec)
self.assertIn("Save A &amp; B &lt;i&gt;", button)
self.assertNotIn("<i>", button)
class SavedPageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.records = records.load_records(ROOT)
cls.doc = read_out("saved/index.html")
def test_holds_every_trail_hidden_for_the_script_to_show(self):
rows = re.findall(r'<li class="entry"( data-[^>]*)>', self.doc)
self.assertEqual(len(rows), len(self.records))
self.assertTrue(all(r.endswith(" hidden") for r in rows))
self.assertIn('<ol class="entries" data-every-trail>', self.doc)
self.assertIn("data-saved-total", self.doc)
self.assertIn("data-saved-page", self.doc)
def test_opens_in_the_order_saved(self):
self.assertIn('data-default-sort="saved"', self.doc)
self.assertIn('<option value="saved" selected>Order saved</option>', self.doc)
# Only this page offers that order.
self.assertNotIn('value="saved"', read_out("index.html"))
def test_its_map_names_what_it_can_draw(self):
fig = re.search(r'<figure class="mapfig[^"]*" data-map="overview"[^>]*>', self.doc).group(0)
self.assertNotIn("data-ids=", fig)
drawable = re.search(r'data-drawable="([^"]*)"', fig).group(1).split()
self.assertEqual(drawable, home.drawable_ids(sorted(self.records, key=home.sort_name)))
caption = self.doc[self.doc.index('<figcaption class="mapfig__caption">'):]
self.assertNotRegex(caption[:caption.index("</figcaption>")], r"\d+ tracks")
def test_link_controls_and_states_are_written(self):
for hook in ("data-saved-share", "data-saved-url", 'data-copy="#saved-url"', 'data-copy-done="Link copied."',
"data-saved-from", "data-saved-merge", "data-saved-dropped", "data-saved-empty", "data-saved-none"):
self.assertIn(hook, self.doc, hook)
self.assertIn(">Copy link</button>", self.doc)
self.assertIn("Save these</button>", self.doc)
self.assertIn("Bookmark it, or send it to another device or another person", self.doc)
self.assertIn('<a class="button button--primary" href="/">Find a trail</a>', self.doc)
def test_says_it_needs_javascript(self):
self.assertIn("Saved trails need JavaScript, which is off or blocked in this browser. "
'<a href="/">See every trail</a>.', self.doc)
def test_not_indexed_and_not_in_the_sitemap(self):
head = self.doc[:self.doc.index("</head>")]
self.assertIn('<meta name="robots" content="noindex">', head)
self.assertNotIn('rel="canonical"', head)
self.assertNotIn('property="og:url"', head)
self.assertNotIn("/saved/", read_out("sitemap.xml"))
self.assertNotIn(saved.PATH, seo.all_paths(self.records, []))
# Every other page keeps its canonical link and is indexable.
other = read_out("about/index.html")
self.assertIn('rel="canonical"', other)
self.assertNotIn('name="robots"', other)
def test_noindex_page_without_base_url(self):
page = layout.layout("T", "", path="/saved/", noindex=True, site=site.Site("N", "T"))
self.assertIn('<meta name="robots" content="noindex">', page)
self.assertNotIn("canonical", page)
def test_the_words_a_visitor_reads(self):
text = re.sub(r"<[^>]+>", " ", self.doc[self.doc.index('<main id="main">'):self.doc.index('<ol class="entries"')])
for word in ("favourite", "favorite", "bookmarks"):
self.assertNotIn(word, text.lower())
self.assertNotRegex(text, r"\bline\b")
class ScriptTest(unittest.TestCase):
"""app.js keeps its promises: one storage key, every access guarded, the events kept."""
@classmethod
def setUpClass(cls):
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
cls.js = f.read()
def test_one_key_every_access_guarded(self):
self.assertIn("var SAVED_KEY = 'lh-saved';", self.js)
for call in ("localStorage.getItem(SAVED_KEY)", "localStorage.setItem(SAVED_KEY", "localStorage.removeItem(SAVED_KEY)"):
i = self.js.index(call)
self.assertIn("try {", self.js[max(0, i - 120):i], call)
self.assertIn("window.addEventListener('storage'", self.js)
def test_the_events_still_fire(self):
self.assertIn("document.dispatchEvent(new Event('olt:units'))", self.js)
self.assertIn("document.dispatchEvent(new Event('olt:theme'))", self.js)
self.assertIn("new CustomEvent('olt:saved'", self.js)
def test_no_request_to_another_site_for_saving(self):
part = self.js[self.js.index("1b. Saved trails"):self.js.index("/* 2. Maps")]
self.assertNotIn("fetch(", part)
self.assertNotIn("XMLHttpRequest", part)
self.assertNotRegex(part, r"https?://")
if __name__ == "__main__":
unittest.main()
+6 -5
View File
@@ -11,7 +11,7 @@ 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, home, words # noqa: E402
from olt import browse, home, layout, words # noqa: E402
from test_hike import fake, render, top_part # noqa: E402
@@ -37,10 +37,11 @@ class DefaultOrderTest(unittest.TestCase):
row.index('<span class="len__km">100 km</span>'))
self.assertIn('data-km="100"', row) # sorting and filtering stay in kilometres
def test_footer_switch_lists_miles_first_and_selects_it(self):
src = read("olt", "layout.py")
self.assertIn('value="mi" checked><span>mi and ft first</span>', src)
self.assertLess(src.index("mi and ft first"), src.index("km and m first"))
def test_header_switch_lists_miles_first_and_selects_it(self):
prefs = layout.prefs()
self.assertIn('value="mi" checked><span aria-hidden="true">mi</span><span class="vh">Miles and feet</span>', prefs)
self.assertLess(prefs.index('value="mi"'), prefs.index('value="km"'))
self.assertNotIn('value="km" checked', prefs)
self.assertIn('value="mi" checked><span>mi</span>', home.UNITS_TOGGLE)
self.assertLess(home.UNITS_TOGGLE.index(">mi<"), home.UNITS_TOGGLE.index(">km<"))