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

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

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

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

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
"""Lists: ready-made selections of trails, each a rule over a trail's attributes (olt/facets.py).
A list is defined once, here, as a test on a trail. No list names a trail by
id: membership follows the records, so a new trail or a new [hike] table moves
trails in and out of lists with no change to this file.
A list is shown (on the home page, on /lists/, and with a page of its own)
only when it is useful with today's trails:
MIN_SIZE at least this many trails (fewer reads as a gap, not a list)
MAX_SHARE at most this share of all trails (more is nearly everything)
Every list has its page at /lists/<key>/, except Routes, which keeps /routes/.
"""
from dataclasses import dataclass
from typing import Callable
from . import common, facets, words
MIN_SIZE = 4
MAX_SHARE = 0.75
LONG_KM = 2000
SHORT_KM = 100
@dataclass(frozen=True)
class List:
key: str
title: str
blurb: str
test: Callable[[dict], bool]
# Order within the list: longest first unless a list says otherwise.
order: Callable[[dict], object] = lambda r: -r["length_km"]
def _mi(km):
return words.fmt_int(words.km_to_mi(km))
def _band(key):
return lambda r: facets.time_band(r) == key
def _days(r):
return facets.time_days(r)[1]
LISTS = (
List("national-scenic-trails", "National Scenic Trails",
"The long trails the United States Congress has named National Scenic Trails.",
facets.is_national),
List("routes", "Routes", facets.ROUTE_DEFINITION,
lambda r: facets.kind(r) == "route"),
List("longest", "The longest",
f"Trails of {LONG_KM:,} km ({_mi(LONG_KM)} mi) or more.",
lambda r: r["length_km"] >= LONG_KM),
List("under-100-km", f"Under {SHORT_KM} km",
f"Trails shorter than {SHORT_KM} km ({_mi(SHORT_KM)} mi).",
lambda r: r["length_km"] < SHORT_KM, order=lambda r: r["length_km"]),
List("a-week-or-less", "A week or less",
"Trails most people walk in a week or less, as a source states it or as estimated from the length.",
_band("week"), order=_days),
List("one-to-two-weeks", "One to two weeks",
"Trails that take one to two weeks, as a source states it or as estimated from the length.",
_band("two-weeks"), order=_days),
List("loops", "Loops", "Trails that finish where they start.",
lambda r: facets.shape(r) == "loop"),
List("with-gpx", "With a GPX to download",
"Trails with a GPX file of the track on their page.",
facets.gpx_here),
List("canada", "In Canada", "Trails in Canada, or crossing into it.",
lambda r: "CA" in common.countries(r)),
List("united-states", "In the United States", "Trails in the United States, or crossing into it.",
lambda r: "US" in common.countries(r)),
List("off-trail", "Cross-country",
"Trails with stretches of walking where there is no trail.",
lambda r: facets.walking(r) in facets.CROSS_COUNTRY),
) + tuple(
List(f"terrain-{t}", label, f"Trails with {t} among their main terrain.",
lambda r, t=t: t in facets.terrain(r))
for t, label in words.TERRAIN.items()
)
def members(lst, records):
return sorted((r for r in records if lst.test(r)), key=lambda r: (lst.order(r), r["name"]))
def is_shown(n, total):
"""The threshold rule: a list is shown when it holds at least MIN_SIZE
trails and no more than MAX_SHARE of all of them."""
return n >= MIN_SIZE and n <= MAX_SHARE * total
def shown(records):
"""[(list, its trails)] for every list that passes is_shown, in LISTS order."""
out = []
for lst in LISTS:
recs = members(lst, records)
if is_shown(len(recs), len(records)):
out.append((lst, recs))
return out
def by_key(key):
return next(lst for lst in LISTS if lst.key == key)
def path(lst):
return "/routes/" if lst.key == "routes" else f"/lists/{lst.key}/"
+7 -31
View File
@@ -129,39 +129,15 @@ def absent_reason_short(rec):
return re.sub(r"^No (?:line|track) is included\.\s*", "", reason) or reason
def regions_html(rec, linked=False):
"""Region codes with their names; optionally each linked to the filtered list."""
parts = []
for code in rec.get("regions", []):
name = words.region_name(code)
if code == words.ALL_CANADA:
text = Markup(esc(name))
href = "/regions/#canada-wide"
else:
text = Markup(f'<abbr title="{esc(name)}">{esc(code)}</abbr>')
href = f"/regions/{words.region_key(code, rec['country']).lower()}/"
if linked:
text = Markup(f'<a href="{esc(href)}">{text}</a>')
parts.append(text)
return Markup(" ".join(parts))
def tags(rec, with_policy=True):
"""Kind, tier and listing tags, and (with_policy) the track policy of a route."""
def badges(rec, *, route_tag=True):
"""The badges a hiker needs on a row or a trail page: Route (linked to what a route is)
and National Scenic Trail. An official trail has no badge for its kind.
route_tag=False leaves the Route badge out (the Routes list, where every row is one)."""
out = []
if is_route(rec):
out.append('<span class="tag tag--route">Person-defined route</span>')
elif rec.get("tier") == "national":
if route_tag and is_route(rec):
out.append('<a class="tag tag--route" href="/routes/">Route</a>')
if rec.get("tier") == "national":
out.append('<span class="tag tag--nst">National Scenic Trail</span>')
else:
out.append('<span class="tag">Designated trail</span>')
tier = rec.get("tier")
if tier in ("short", "deferred", "candidate"):
out.append(f'<span class="tag tag--quiet">{esc(words.label(words.TIERS, tier))}</span>')
if str(rec.get("wave")) == "held":
out.append('<span class="tag tag--quiet">Held</span>')
if is_route(rec) and with_policy:
out.append(policy_chip(policy(rec)))
return Markup("".join(out))
+136 -25
View File
@@ -8,7 +8,7 @@ import collections
import os
import re
from . import common, md, words
from . import common, elevation, facets, md, words
from .markup import Markup, esc
REAL_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -178,7 +178,23 @@ def sources_page(records, site, repo_root):
return Markup(f'{esc(words.label(words.LICENCES, k))} <code class="raw">{esc(k)}</code>')
head = ('<thead><tr><th scope="col">{0}</th><th scope="col">Records</th>'
'<th scope="col">With a track</th><th scope="col">Trails and routes</th></tr></thead>')
'<th scope="col">With a track</th><th scope="col">Trails</th></tr></thead>')
elev_models = {}
for r in records:
src = (elevation.get(r) or {}).get("source") or {}
if src.get("attribution"):
key = (src.get("model", ""), src.get("url", ""), src["attribution"])
elev_models[key] = elev_models.get(key, 0) + 1
elev_credit = ""
if elev_models:
items = ""
for (model, url, attribution), n in sorted(elev_models.items()):
model_html = (f'<a href="{esc(url)}">{esc(model)}</a>' if url else esc(model)) if model else "The elevation model"
items += (f'<p>{model_html}, used for {n} trail{"s" if n != 1 else ""}.</p>'
f'<p>{esc(attribution)}</p>')
elev_credit = (f'<div class="doc-block"><h3>Elevation model</h3>'
f'<p>The elevation figures and profiles on the trail pages were computed '
f'from each track and this model. Its credit, as it gives it:</p>{items}</div>')
computed = f"""<div class="container section">
<div class="section-head"><h2 id="sources-at-a-glance">At a glance</h2>
<p>Counted from the {len(records)} records. Each trail page names its own source, licence and credit.
@@ -191,10 +207,11 @@ def sources_page(records, site, repo_root):
<div class="doc-block"><h3>By track source</h3><div class="table-wrap"><table>
{head.format("Track source")}
<tbody>{group_rows(by_source, source_label)}</tbody></table></div></div>
{elev_credit}
</div>"""
doc_html = render_doc(read_doc(repo_root, "SOURCES.md"), site, drop_h1=True)
body = (f'<div class="page-head"><div class="container"><header class="titleblock">'
f'<div class="titleblock__text"><p class="kicker">Provenance</p><h1>Sources</h1>'
body = (f'<div class="page-head"><div class="container">{BREAD}<li aria-current="page">Sources</li></ol></nav><header class="titleblock">'
f'<div class="titleblock__text"><h1>Sources</h1>'
f'<p class="page-head__lede">Where the tracks come from, and the terms each source states.</p>'
f'</div></header></div></div>{computed}'
f'<div class="container section"><div class="prose doc">{doc_html}</div></div>')
@@ -224,8 +241,8 @@ def logos_page(records, site, repo_root):
<div><dt>Taken from</dt><dd>{src_html}</dd></div></dl></div>
</li>"""
counts = collections.Counter(r.get("shield", {}).get("status", "") for r in records)
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">Marks</p><h1>Logos</h1>
body = f"""<div class="page-head"><div class="container">{BREAD}<li aria-current="page">Logos</li></ol></nav><header class="titleblock">
<div class="titleblock__text"><h1>Logos</h1>
<p class="page-head__lede">Logos are shown only to identify each trail. They belong to their holders.</p>
</div></header></div></div>
<div class="container section"><div class="prose doc">{notice_html}{f'<p><a href="{esc(site.removal_url)}">Ask for a track or logo to be removed, or its credit changed</a>.</p>' if site.is_github else ""}</div></div>
@@ -238,27 +255,121 @@ logo not found (<code class="raw">logo-not-found</code>).</p></div>"""
return "Logos", "Trail logos, their holders, and how a holder can ask for removal.", Markup(body)
BREAD = Markup('<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/about/">About</a></li>')
ABOUT_PARTS = (
# (anchor or path, title, what it is)
("#what-this-is", "What this is", "A guide to the long trails, built from an open dataset"),
("#how-trails-are-chosen", "How trails are chosen", "The rule, and what held, deferred and candidate mean"),
("#when-a-gpx-is-included", "When a GPX is included", "Whose tracks may be passed on, and routes' authors' terms"),
("/data/", "Data and downloads", "Every trail and track in bulk, the per-trail files and the licences"),
("/sources/", "Sources and their terms", "Where each track comes from, and the terms each source states"),
("/logos/", "Logos", "Each trail's logo, who holds it, and how to ask for removal"),
("/data/schema/", "Record schema", "Every field of a trail's record (trail.toml) and what it means"),
("/data/changelog/", "Changelog", "What changed, release by release"),
("#correct-or-add", "Correct or add a trail", "Report a problem, suggest a trail, or edit the data"),
)
def _count_line(records, key, value):
return sum(1 for r in records if str(r.get(key, "")) == value)
def about_page(records, site, repo_root):
"""(title, description, body) for /about/."""
"""(title, description, body) for /about/: the hub for the project and the dataset."""
readme = read_doc(repo_root, "README.md")
main = link_requests(render_sections(readme, site,
["What this is, and what it is not", "Inclusion rule",
"How to use it", "Report an error", "Licences", "Sources"]), site)
found = sections_map(readme)
def quoted(title, heading):
body = found.get(title)
if body is None:
return ""
return link_requests(render_doc(f"### {heading}\n\n{body}", site), site)
what = quoted("What this is, and what it is not", "The dataset’s own words")
rule = quoted("Inclusion rule", "The rule as the dataset states it")
rest = link_requests(render_sections(readme, site, ["How to use it", "Licences", "Report an error"]), site)
contrib = render_doc(read_doc(repo_root, "CONTRIBUTING.md"), site, heading_offset=1)
extra = ""
cards = "".join(
f'<li><a href="{esc(href)}">{esc(title)}</a><small>{esc(what_)}</small></li>'
for href, title, what_ in ABOUT_PARTS)
n = len(records)
routes = sum(1 for r in records if common.is_route(r))
tiers = collections.Counter(r.get("tier", "") for r in records)
held = _count_line(records, "wave", "held")
tier_rows = "".join(
f'<tr><td>{esc(words.label(words.TIERS, t))} <code class="raw">{esc(t)}</code></td>'
f'<td>{esc(words.meaning(words.TIERS, t))}.</td><td class="num">{tiers[t]}</td></tr>'
for t in ("national", "regional", "short", "deferred", "candidate") if tiers[t])
policies = collections.Counter(common.policy(r) for r in records if common.is_route(r))
policy_rows = "".join(
f'<tr><td>{common.policy_chip(p)}</td><td>{esc(words.POLICIES[p][1])}. {esc(words.POLICIES[p][2])}</td>'
f'<td class="num">{policies[p]}</td></tr>'
for p in ("open", "sold", "withheld", "unclear") if policies[p])
lines = sum(1 for r in records if common.has_line(r))
forms = ""
if site.repo_url and site.is_github:
extra = (f'<p><a href="{esc(site.correction_url())}">Report a problem</a> with a record, or '
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a> that is missing: '
f'short forms, no git needed. Or fix or add a trail yourself in the source repository.</p>')
forms = (f'<ul class="linklist">'
f'<li><a href="{esc(site.correction_url())}">Report a problem</a><small>A short form, no git needed. '
f'Every trail page also has its own link, with the trail filled in.</small></li>'
f'<li><a href="{esc(site.new_trail_url)}">Suggest a trail</a><small>A short form for a trail that is missing</small></li>'
f'<li><a href="{esc(site.removal_url)}">Ask for a track or logo to be removed</a><small>For the holder of a track or a logo</small></li>'
f'<li><a href="{esc(site.repo_url)}">Edit the data yourself</a><small>The source repository: one text file per trail</small></li>'
f'</ul>')
elif site.issues_url:
extra = f'<p><a href="{esc(site.issues_url)}">Open an issue</a> to report an error.</p>'
if site.repo_url:
extra += f'<p>Source repository: <a href="{esc(site.repo_url)}">{esc(site.repo_url)}</a>.</p>'
forms = f'<p><a href="{esc(site.issues_url)}">Open an issue</a> to report an error.</p>'
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">The project</p><h1>About {esc(site.name)}</h1>
<p class="page-head__lede">{esc(site.tagline)}.</p></div></header></div></div>
<div class="container section"><div class="prose doc">{main}{extra}{contrib}</div></div>"""
return "About", f"What {site.name} is and is not, the inclusion rule, licences and how to contribute.", Markup(body)
<div class="titleblock__text"><h1>About {esc(site.name)}</h1>
<p class="page-head__lede">{esc(site.tagline)}. Everything about the project and the data behind it is here.</p></div></header>
<nav class="about-hub" aria-label="About this site"><ul class="linklist about-hub__list">{cards}</ul></nav>
</div></div>
<div class="container section"><div class="prose doc">
<section aria-labelledby="what-this-is"><h2 id="what-this-is">What this is</h2>
<p>{esc(site.name)} lists {n} long-distance trails in the United States and Canada: where each one goes,
how long it is and takes, when to walk it, and where to get its track. It is built, page by page, from an
open dataset of one text file per trail. Everything a page says about a trail comes from that file.
{f'The dataset is kept in a <a href="{esc(site.repo_url)}">public repository</a>, where anyone can propose a change.' if site.repo_url else ""}</p>
<p>The dataset calls each trail a <em>record</em>, and the pages under About use its terms. The rest of the
site calls them trails.</p>
{what}
</section>
<section aria-labelledby="how-trails-are-chosen"><h2 id="how-trails-are-chosen">How trails are chosen</h2>
<p>A trail is listed when it is a named, continuous walk, or a named loop, of at least 80&nbsp;km (50&nbsp;miles)
in the United States or Canada. It is either an official trail, looked after as one trail by a land agency or
a trail association, or a route: {esc(facets.ROUTE_DEFINITION[0].lower() + facets.ROUTE_DEFINITION[1:])}
{routes} of the {n} trails are routes. Every National Scenic Trail is listed, and a few well-known multi-day
trails between 60 and 80&nbsp;km.</p>
<p>Each record has a <em>tier</em>, which says why it is listed. A record can also be <em>held</em>: listed,
but with something about it not yet settled, which its note says.</p>
<div class="table-wrap"><table><thead><tr><th scope="col">Tier</th><th scope="col">What it means</th><th scope="col">Records</th></tr></thead>
<tbody>{tier_rows}<tr><td>Held <code class="raw">wave = "held"</code></td><td>{esc(words.meaning(words.WAVES, "held"))}. Any tier can be held.</td><td class="num">{held}</td></tr></tbody></table></div>
<p>These states are for keeping the dataset. They are not shown when browsing trails, and they do not change
what a trail page says about walking it. Each trail page shows its own under &ldquo;About this data&rdquo;.</p>
{rule}
</section>
<section aria-labelledby="when-a-gpx-is-included"><h2 id="when-a-gpx-is-included">When a GPX is included</h2>
<p>A track is included, as GPX and GeoJSON, only where its source&rsquo;s terms allow passing it on.
{lines} of the {n} trails have one. Where there is none, the trail&rsquo;s page says why and where to look.
Each track keeps its source&rsquo;s terms; the credit and licence are shown beside every map and download.</p>
<p>A route&rsquo;s track follows its author&rsquo;s choice. The dataset records that choice as the route&rsquo;s
<em>track policy</em>:</p>
<div class="table-wrap"><table><thead><tr><th scope="col">Track policy</th><th scope="col">What it means here</th><th scope="col">Routes</th></tr></thead>
<tbody>{policy_rows}</tbody></table></div>
<p>The author of a route who wants its record changed or removed can ask; see <a href="/logos/">Logos</a> for how,
or use the links below.</p>
</section>
<section aria-labelledby="correct-or-add"><h2 id="correct-or-add">Correct or add a trail</h2>
<p>Every trail page has a &ldquo;Report a problem&rdquo; link. Please say where a correction can be checked:
a source page, a map, or a measured track.</p>
{forms}
{rest}
{contrib}
</section>
</div></div>"""
return "About", f"What {site.name} is, how trails are chosen, the data and its sources, and how to correct or add a trail.", Markup(body)
def _size(out_dir, relpath):
@@ -337,8 +448,8 @@ def data_page(records, site, repo_root, out_dir):
]
lrow = "".join(f'<tr><td>{esc(a)}</td><td>{esc(b)}</td><td><a href="{esc(c)}">{esc(c)}</a></td></tr>'
for a, b, c in lic_rows)
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">Downloads</p><h1>Data</h1>
body = f"""<div class="page-head"><div class="container">{BREAD}<li aria-current="page">Data</li></ol></nav><header class="titleblock">
<div class="titleblock__text"><h1>Data and downloads</h1>
<p class="page-head__lede">Bulk files, the stable per-trail URLs, and the licences.</p></div></header></div></div>
<div class="container section">
<div class="section-head"><h2>Bulk downloads</h2><p>{len(records)} records. Sizes are this build's.</p></div>
@@ -373,7 +484,7 @@ def data_page(records, site, repo_root, out_dir):
def schema_page(site, repo_root):
doc_html = render_doc(read_doc(repo_root, "docs/schema.md"), site, drop_h1=True)
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/data/">Data</a></li>
{BREAD}<li><a href="/data/">Data</a></li>
<li aria-current="page">Record schema</li></ol></nav>
<header class="titleblock"><div class="titleblock__text"><p class="kicker">Reference</p>
<h1>Record schema</h1></div></header></div></div>
@@ -384,7 +495,7 @@ def schema_page(site, repo_root):
def changelog_page(site, repo_root):
doc_html = render_doc(read_doc(repo_root, "CHANGELOG.md"), site, drop_h1=True)
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/data/">Data</a></li>
{BREAD}<li><a href="/data/">Data</a></li>
<li aria-current="page">Changelog</li></ol></nav>
<header class="titleblock"><div class="titleblock__text"><p class="kicker">Reference</p>
<h1>Changelog</h1></div></header></div></div>
+286
View File
@@ -0,0 +1,286 @@
"""Elevation facts and the profile, from a trail's elevation.json (docs/schema.md).
The file beside each record holds figures computed from its track and a public
elevation model. This module loads it, states the rules that decide what a page
may honestly show, and draws the profile as SVG at build time.
Rules, all on the file's own fields:
coverage below LOW_COVERAGE: the figures describe the track only.
coverage above HIGH_COVERAGE: the track includes more than the trail, so
the climb is overstated.
parts above PROFILE_MAX_PARTS: the parts are not in walking order, so no
profile is drawn; the figures are still shown.
descent is shown beside the climb only when it differs by more than
DESCENT_DIFF of the larger figure.
"""
import json
import math
import os
from collections import Counter
from . import words
from .markup import Markup, esc
LOW_COVERAGE = 0.85
HIGH_COVERAGE = 1.15
PROFILE_MAX_PARTS = 10
DESCENT_DIFF = 0.05
COMPUTED_NOTE = "Computed from the track."
_REQUIRED = ("highest", "lowest", "ascent_m", "descent_m", "track_km",
"published_km", "coverage", "parts", "orientation", "profile", "source")
def load_file(root, tid):
"""The parsed elevation.json of one trail, or None when it has none or it
does not hold the fields a page needs."""
path = os.path.join(root, tid, "elevation.json")
if not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
except (OSError, ValueError):
return None
if not isinstance(data, dict) or any(k not in data for k in _REQUIRED):
return None
if not all(isinstance(data[k], dict) and "m" in data[k] for k in ("highest", "lowest")):
return None
if not isinstance(data.get("source"), dict) or not isinstance(data.get("profile"), list):
return None
return data
def get(rec):
"""A record's elevation facts (derived.elevation), or None."""
value = rec.get("derived", {}).get("elevation")
return value if isinstance(value, dict) else None
def direction_words(elev):
""""walking south to north", from the file's orientation."""
text = str(elev.get("orientation", "")).replace("-", " ")
return f"walking {text}" if text else ""
def coverage_kind(elev):
""""partial" well under 1, "over" well over 1, else ""."""
cov = elev.get("coverage")
if not isinstance(cov, (int, float)):
return ""
if cov < LOW_COVERAGE:
return "partial"
if cov > HIGH_COVERAGE:
return "over"
return ""
def coverage_percent(elev):
""""about 59%", or "less than 1%" for a track that barely exists."""
pct = (elev.get("coverage") or 0) * 100
if pct < 1:
return "less than 1%"
return f"about {round(pct):,}%"
def coverage_caveat(elev):
"""What the coverage means for the figures, or "" when it is near 1."""
kind = coverage_kind(elev)
if kind == "partial":
return ("The elevation figures are for the track only. The track covers "
f"{coverage_percent(elev)} of the published length.")
if kind == "over":
return ("The track is longer than the published length "
f"({coverage_percent(elev)} of it). It includes more than the trail, such as "
"side trails or alternates, so the climb is overstated.")
return ""
def show_descent(elev):
"""True when descent differs from ascent by more than a few percent."""
up, down = elev.get("ascent_m") or 0, elev.get("descent_m") or 0
bigger = max(up, down)
return bool(bigger) and abs(up - down) / bigger > DESCENT_DIFF
def show_profile(elev):
"""True when a profile may be drawn: few enough parts to be in walking order."""
return (elev.get("parts") or 0) <= PROFILE_MAX_PARTS and len(elev.get("profile") or []) >= 2
def parts_caveat(elev):
"""Why no profile is drawn, when the track is in too many parts."""
if len(elev.get("profile") or []) < 2:
return "No profile is drawn. The track has too few sampled points to draw one."
parts = elev.get("parts") or 0
if parts <= PROFILE_MAX_PARTS:
return ""
return (f"No profile is drawn. The track is in many parts ({parts} in the elevation "
"sampling) and they are not in walking order, so a line through them would not "
"be the walk. The figures above are still from the whole track, with no climb "
"counted across a gap.")
def plain_elevation(m):
""""2,025 m (6,644 ft)", for a sentence or a text alternative."""
return f"{words.fmt_int(m)} m ({words.fmt_int(m / words.M_PER_FT)} ft)"
def plain_length(km):
return f"{words.fmt_km1(km)} km ({words.fmt_int(words.km_to_mi(km))} mi)"
def is_sea_level(point):
return (point or {}).get("m") == 0
def summary_sentence(elev, loop=False):
"""The facts in one sentence: the profile's text alternative."""
high, low = elev["highest"]["m"], elev["lowest"]["m"]
direction = "" if loop else f", {direction_words(elev)}"
low_text = "sea level" if low == 0 else plain_elevation(low)
text = (f"Computed from the track{direction}, the trail climbs "
f"{plain_elevation(elev['ascent_m'])} in total over {plain_length(elev['track_km'])} "
f"of track, between a low point of {low_text} and a high point of {plain_elevation(high)}")
if show_descent(elev):
text += f", and descends {plain_elevation(elev['descent_m'])}"
return text + "."
# The profile ----------------------------------------------------------------
def segments(profile, part_starts=()):
"""The profile split into its parts. A part's first point repeats the
distance of the point before it (docs/schema.md), and part_starts_km names
those distances; a new part starts there, never joined to the last."""
starts = Counter(part_starts or ())
out, current, prev = [], [], None
for point in profile or ():
dist = point[0]
if current and dist <= prev and (dist < prev or starts.get(dist, 0) or not starts):
if starts.get(dist, 0):
starts[dist] -= 1
out.append(current)
current = []
current.append(point)
prev = dist
if current:
out.append(current)
return out
def _nice_step(span, target=5):
if span <= 0:
return 1.0
raw = span / target
mag = 10 ** math.floor(math.log10(raw))
for mult in (1, 2, 5, 10):
if raw <= mult * mag:
return float(mult * mag)
return float(10 * mag)
def _ticks(lo, hi, target=5):
step = _nice_step(hi - lo, target)
value = math.ceil(lo / step) * step
out = []
while value <= hi + step * 1e-9:
out.append(round(value, 10))
value += step
return out, step
def _fmt_tick(value, step):
if step >= 1:
return f"{round(value):,}"
text = f"{value:.2f}".rstrip("0").rstrip(".")
return text
W, H = 680, 270
LEFT, RIGHT, TOP, BOTTOM = 58, 14, 14, 40
def profile_svg(elev, loop=False):
"""The profile as inline SVG, drawn now, not by a script. Both unit systems
are drawn; CSS shows one, through the same len__km / len__mi pair and the
reader's unit preference as every length on the site."""
profile = elev.get("profile") or []
if len(profile) < 2:
return Markup("")
plot_w, plot_h = W - LEFT - RIGHT, H - TOP - BOTTOM
x_max = max(float(elev.get("track_km") or 0), max(p[0] for p in profile), 0.001)
low_m = min(float(elev["lowest"]["m"]), min(p[1] for p in profile))
high_m = max(float(elev["highest"]["m"]), max(p[1] for p in profile))
span = high_m - low_m
pad = max(10.0, span * 0.06) if span else 10.0
y_lo = max(0.0, low_m - pad) if low_m >= 0 else low_m - pad
y_hi = high_m + pad
if y_hi <= y_lo:
y_hi = y_lo + 20
def x(dist_km):
return LEFT + dist_km / x_max * plot_w
def y(elev_m):
return TOP + (y_hi - elev_m) / (y_hi - y_lo) * plot_h
paths = []
for seg in segments(profile, elev.get("part_starts_km")):
if len(seg) < 2:
continue
cmd = "M" + " L".join(f"{x(float(d)):.1f} {y(float(m)):.1f}" for d, m in seg)
paths.append(cmd)
line = f'<path class="elev-profile__line" d="{" ".join(paths)}"/>'
high_pt = max(profile, key=lambda p: p[1])
low_pt = min(profile, key=lambda p: p[1])
marks = "".join(
f'<circle class="elev-profile__mark" cx="{x(float(d)):.1f}" cy="{y(float(m)):.1f}" r="3.5"/>'
for d, m in (high_pt, low_pt))
def axis_group(system):
"""Ticks, grid lines and axis titles for one unit system."""
out = []
if system == "km":
yticks, ystep = _ticks(y_lo, y_hi, 4)
yvals = [(t, t) for t in yticks]
xticks, xstep = _ticks(0, x_max, 5)
xvals = [(t, t) for t in xticks]
ytitle, xtitle = "Elevation (m)", "Distance along the track (km)"
else:
yticks, ystep = _ticks(y_lo / words.M_PER_FT, y_hi / words.M_PER_FT, 4)
yvals = [(t * words.M_PER_FT, t) for t in yticks]
xticks, xstep = _ticks(0, words.km_to_mi(x_max), 5)
xvals = [(t * words.KM_PER_MI, t) for t in xticks]
ytitle, xtitle = "Elevation (ft)", "Distance along the track (mi)"
for elev_m, label in yvals:
yy = y(elev_m)
if TOP - 1 <= yy <= TOP + plot_h + 1:
out.append(f'<line class="elev-profile__grid" x1="{LEFT}" y1="{yy:.1f}" '
f'x2="{LEFT + plot_w}" y2="{yy:.1f}"/>')
out.append(f'<text class="elev-profile__tick" x="{LEFT - 6}" y="{yy + 4:.1f}" '
f'text-anchor="end">{esc(_fmt_tick(label, ystep))}</text>')
for dist_km, label in xvals:
xx = x(dist_km)
if LEFT - 1 <= xx <= LEFT + plot_w + 1:
anchor = "start" if label == 0 else "middle"
out.append(f'<text class="elev-profile__tick" x="{xx:.1f}" y="{TOP + plot_h + 18}" '
f'text-anchor="{anchor}">{esc(_fmt_tick(label, xstep))}</text>')
middle_y = TOP + plot_h / 2
out.append(f'<text class="elev-profile__axis" x="14" y="{middle_y:.1f}" text-anchor="middle" '
f'transform="rotate(-90 14 {middle_y:.1f})">{esc(ytitle)}</text>')
out.append(f'<text class="elev-profile__axis" x="{LEFT + plot_w / 2:.1f}" y="{H - 4}" '
f'text-anchor="middle">{esc(xtitle)}</text>')
cls = "len__km" if system == "km" else "len__mi"
return f'<g class="{cls}">{"".join(out)}</g>'
axes = (f'<line class="elev-profile__frame" x1="{LEFT}" y1="{TOP + plot_h}" '
f'x2="{LEFT + plot_w}" y2="{TOP + plot_h}"/>'
f'<line class="elev-profile__frame" x1="{LEFT}" y1="{TOP}" '
f'x2="{LEFT}" y2="{TOP + plot_h}"/>')
return Markup(
f'<svg class="elev-profile" viewBox="0 0 {W} {H}" role="img" '
f'aria-label="{esc(summary_sentence(elev, loop))}" focusable="false">'
f"{axis_group('km')}{axis_group('mi')}{axes}{line}{marks}</svg>")
+310
View File
@@ -0,0 +1,310 @@
"""The attributes a hiker sees for a trail, each with one name used on every page.
Where the states and provinces, grouped into places (PLACE_GROUPS)
Length length_km
Time [hike].days as a source states it, else an estimate from the length
Season [hike].months (the phrase on the trail page is [hike].season)
Terrain [hike].terrain
Kind official trail, or route (the [route] table)
Walking [hike].travel
Shape [hike].shape
GPX one status per trail, from the track and, for a route, its author's terms
Designation National Scenic Trail (tier "national"), shown as a badge
Every value here is computed from the records by rule. Nothing names a trail.
The dataset's own terms (tier, wave, source status, track policy) are not
attributes a hiker filters by; they stay in "About this data" on each trail
page and on the pages under About.
"""
import math
from . import common, hike, words
# Facet names, exactly as every page shows them.
WHERE, LENGTH, TIME, SEASON, TERRAIN, KIND, WALKING, SHAPE, GPX = (
"Where", "Length", "Time", "Season", "Terrain", "Kind", "Walking", "Shape", "GPX")
# A facet a trail may have no value for is offered as a filter only when at
# least this share of all trails has a value.
COVERAGE_MIN = 1 / 3
# Where ----------------------------------------------------------------------
# (key, name, [region keys]). Every state, province and territory code is in
# exactly one group (test_facets checks it against words.US_STATES and
# words.CA_PROVINCES, and against every code the records use).
PLACE_GROUPS = (
("west-coast", "West Coast", ["US-WA", "US-OR", "US-CA", "US-HI"]),
("mountain-west", "Mountain West", ["US-ID", "US-MT", "US-WY", "US-NV", "US-UT", "US-CO"]),
("southwest", "Southwest", ["US-AZ", "US-NM", "US-TX", "US-OK"]),
("midwest", "Midwest", ["US-ND", "US-SD", "US-NE", "US-KS", "US-MN", "US-IA", "US-MO",
"US-WI", "US-IL", "US-MI", "US-IN", "US-OH"]),
("south", "South", ["US-AR", "US-LA", "US-MS", "US-AL", "US-TN", "US-KY", "US-GA",
"US-FL", "US-SC", "US-NC"]),
("mid-atlantic", "Mid-Atlantic", ["US-NY", "US-NJ", "US-PA", "US-DE", "US-MD", "US-DC",
"US-VA", "US-WV"]),
("new-england", "New England", ["US-CT", "US-RI", "US-MA", "US-VT", "US-NH", "US-ME"]),
("north", "Alaska and the North", ["US-AK", "CA-YT", "CA-NT", "CA-NU"]),
("western-canada", "Western Canada", ["CA-BC", "CA-AB", "CA-SK", "CA-MB"]),
("central-canada", "Central Canada", ["CA-ON", "CA-QC"]),
("atlantic-canada", "Atlantic Canada", ["CA-NB", "CA-NS", "CA-PE", "CA-NL"]),
)
GROUP_OF = {key: g for g, _, keys in PLACE_GROUPS for key in keys}
GROUP_NAME = {g: name for g, name, _ in PLACE_GROUPS}
# A trail that names "all provinces and territories" crosses Canada: it is in
# every Canadian group, but on no single province's page.
ACROSS_CANADA = "CA-*"
ACROSS_CANADA_NAME = "Across Canada"
def place_keys(rec):
"""The trail's states and provinces as keys ("US-AZ", "CA-ON", "CA-*"), in record order."""
out = []
for code in rec.get("regions", []):
key = words.region_key(code, rec["country"])
if key not in out:
out.append(key)
return out
def place_groups(rec):
"""The place groups a trail is in, in PLACE_GROUPS order."""
keys = set(place_keys(rec))
found = {GROUP_OF[k] for k in keys if k in GROUP_OF}
if ACROSS_CANADA in keys:
found |= {GROUP_OF[k] for k in GROUP_OF if k.startswith("CA-")}
return [g for g, _, _ in PLACE_GROUPS if g in found]
def place_name(key):
""""US-AZ" -> "Arizona"; "CA-*" -> "Across Canada"."""
if key == ACROSS_CANADA:
return ACROSS_CANADA_NAME
return words.region_name(key.split("-", 1)[1])
def place_path(key):
"""The page of a state or province (the /regions/ URLs are kept)."""
if key == ACROSS_CANADA:
return "/regions/#across-canada"
return f"/regions/{key.lower()}/"
def where_tokens(rec):
"""Every Where value a trail matches: its countries, states and provinces, and groups."""
return common.countries(rec) + place_keys(rec) + ["g:" + g for g in place_groups(rec)]
# Time -----------------------------------------------------------------------
PACE_KM = (20, 30) # km a day on trail
PACE_KM_CROSS = (12, 20) # km a day where much of it is cross-country
CROSS_COUNTRY = ("some-cross-country", "mostly-cross-country")
# (key, label, most days). A trail falls in the band of the middle of its range.
TIME_BANDS = (
("week", "A week or less", 7),
("two-weeks", "One to two weeks", 14),
("month", "Two to four weeks", 28),
("months", "One to three months", 91),
("long", "More than three months", math.inf),
)
TIME_LABEL = {k: label for k, label, _ in TIME_BANDS}
def pace(rec):
return PACE_KM_CROSS if hike.table(rec).get("travel") in CROSS_COUNTRY else PACE_KM
def time_days(rec):
"""(fewest, most, estimated): the days to walk it all. As a source states it in
[hike].days; otherwise estimated from the length at pace(rec) km a day."""
stated = hike.table(rec).get("days")
if isinstance(stated, (int, float)):
stated = [stated]
stated = [d for d in (stated or []) if isinstance(d, (int, float)) and d > 0]
if stated:
return min(stated), max(stated), False
slow, fast = pace(rec)
km = rec["length_km"]
return max(1, math.ceil(km / fast)), max(1, math.ceil(km / slow)), True
def time_band(rec):
lo, hi, _ = time_days(rec)
mid = (lo + hi) / 2
for key, _, most in TIME_BANDS:
if mid <= most:
return key
return TIME_BANDS[-1][0]
def time_text(rec):
""""5 to 7 months"; "About 2 to 3 weeks" when estimated."""
lo, hi, est = time_days(rec)
text = words.fmt_days([lo, hi])
if est and not text.startswith("about"):
text = "about " + text
return text[:1].upper() + text[1:]
def estimate_note(rec):
"""Says how an estimated time was worked out; "" when a source states it."""
if not time_days(rec)[2]:
return ""
slow, fast = pace(rec)
mi = f"{round(slow / words.KM_PER_MI)} to {round(fast / words.KM_PER_MI)} mi"
return f"Estimated from the length, at {slow} to {fast} km ({mi}) a day."
# Season ---------------------------------------------------------------------
MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December")
def months(rec):
m = hike.table(rec).get("months")
return sorted({x for x in (m or []) if isinstance(x, int) and 1 <= x <= 12})
def season_text(rec):
"""The phrase on the trail page: [hike].season, else built from the months."""
phrase = (hike.table(rec).get("season") or "").strip()
if phrase:
return phrase[:1].upper() + phrase[1:]
ms = months(rec)
if not ms:
return ""
if len(ms) == 12:
return "All year"
return words.join_names(MONTHS[m - 1] for m in ms)
# Terrain, Walking, Shape ----------------------------------------------------
TERRAIN_VALUES = words.TERRAIN
WALKING_VALUES = {
"trail": "On trail",
"trail-and-road": "Trail and road",
"some-cross-country": "Some cross-country",
"mostly-cross-country": "Mostly cross-country",
}
WALKING_HINT = {
"trail": "On built or maintained trail all or nearly all the way",
"trail-and-road": "Trail, with long stretches on roads",
"some-cross-country": "Mostly trail or road, with stretches that have no trail",
"mostly-cross-country": "No trail for most of the way",
}
SHAPES = {"point-to-point": "End to end", "loop": "Loop", "network": "Network"}
def terrain(rec):
return hike.terrain(rec)
def walking(rec):
v = hike.table(rec).get("travel", "")
return v if v in WALKING_VALUES else ""
def shape(rec):
v = hike.shape(rec)
return v if v in SHAPES else ""
# Kind -----------------------------------------------------------------------
KINDS = {"trail": "Official trail", "route": "Route"}
ROUTE_DEFINITION = ("A route is a trail that a hiker worked out and published. No agency or "
"association looks after it as one trail, and there may be no signs for it.")
def kind(rec):
return "route" if common.is_route(rec) else "trail"
def route_by(rec):
""""Route by Andrew Skurka, 2018"; "" for an official trail."""
if not common.is_route(rec):
return ""
r = rec.get("route", {})
who = r.get("creator", "")
if not who:
return "Route"
return f"Route by {who}" + (f", {r['year']}" if r.get("year") else "")
def author(rec):
return rec.get("route", {}).get("creator", "") if common.is_route(rec) else ""
def is_national(rec):
return rec.get("tier") == "national"
# GPX ------------------------------------------------------------------------
GPX_STATUS = {
"here": "GPX to download here",
"partial": "Partial GPX to download here",
"free": "Free from its author",
"sold": "Sold by its author",
"unpublished": "Not published",
"elsewhere": "Not here, see the official site",
}
# The short form in a list row.
GPX_SHORT = {
"here": "GPX here",
"partial": "Partial GPX here",
"free": "Free from its author",
"sold": "Sold by its author",
"unpublished": "Not published",
"elsewhere": "See the official site",
}
def gpx(rec):
"""The trail's one GPX status (a key of GPX_STATUS)."""
if common.has_line(rec):
return "partial" if common.line_short(rec) else "here"
if common.is_route(rec):
return {"open": "free", "sold": "sold", "withheld": "unpublished"}.get(common.policy(rec), "elsewhere")
return "elsewhere"
def gpx_here(rec):
return gpx(rec) in ("here", "partial")
# Coverage -------------------------------------------------------------------
# facet key -> (name, the trail's values: a list, empty when it has none)
OPTIONAL = {
"season": (SEASON, months),
"terrain": (TERRAIN, terrain),
"walking": (WALKING, lambda r: [walking(r)] if walking(r) else []),
"shape": (SHAPE, lambda r: [shape(r)] if shape(r) else []),
}
# The noun for "12 trails have no ... on file".
MISSING_NOUN = {"season": "season", "terrain": "terrain", "walking": "walking", "shape": "shape"}
def coverage(records, key):
"""(trails with a value, trails without) for an optional facet."""
fn = OPTIONAL[key][1]
have = sum(1 for r in records if fn(r))
return have, len(records) - have
def offered(records, key):
"""True when the facet is offered as a filter: at least COVERAGE_MIN of trails have a value."""
have, _ = coverage(records, key)
return bool(records) and have >= COVERAGE_MIN * len(records)
def missing_text(n, key):
""""12 trails have no season on file."; "" for none."""
if not n:
return ""
return f"{n} trail{'s' if n != 1 else ''} {'has' if n == 1 else 'have'} no {MISSING_NOUN[key]} on file."
+95
View File
@@ -0,0 +1,95 @@
"""The hiker facts of a record: its optional [hike] table (docs/schema.md).
Every field is optional, and most records have no [hike] table at all, so
every function here returns "" (or an empty list) when its field is missing.
"""
import re
from . import words
# Words after which a full stop does not end a sentence ("Mt. Rainier", "U.S. Forest Service").
_ABBREVIATIONS = {"mt", "st", "ft", "dr", "mr", "mrs", "ms", "jr", "sr", "no", "vs", "ca", "approx",
"u.s", "e.g", "i.e", "etc", "hwy", "rd", "mi", "km"}
_SENTENCE_END = re.compile(r"[.!?](?=\s+[A-Z0-9“\"(])")
def table(rec):
value = rec.get("hike")
return value if isinstance(value, dict) else {}
def has(rec):
return bool(table(rec))
def summary(rec):
return (table(rec).get("summary") or "").strip()
def first_sentence(text):
"""The first sentence of a text: "A. B." -> "A.". Initials and common
abbreviations ("Mt.", "U.S.") do not end a sentence."""
text = (text or "").strip()
for m in _SENTENCE_END.finditer(text):
word = re.search(r"([\w.]+)$", text[:m.start()])
w = word.group(1).lower() if word else ""
if w in _ABBREVIATIONS or (len(w) == 1 and w.isalpha()):
continue
return text[:m.end()]
return text
def one_line(rec):
"""The one-line description: the first sentence of the summary, or ""."""
return first_sentence(summary(rec))
def days(rec):
return words.fmt_days(table(rec).get("days"))
def days_max(rec):
"""The most days it usually takes, or None."""
d = table(rec).get("days")
if isinstance(d, (int, float)):
d = [d]
d = [x for x in (d or []) if isinstance(x, (int, float)) and x > 0]
return max(d) if d else None
def shape(rec):
return table(rec).get("shape", "")
def terrain(rec):
return [t for t in table(rec).get("terrain", []) if t in words.TERRAIN]
def official_url(rec):
url = table(rec).get("official_url", "")
return url if isinstance(url, str) and url.startswith(("http://", "https://")) else ""
def ends(rec):
"""(label, text) for where it starts and ends, or None.
point-to-point (or no shape): "Start and end", "A to B"; loop: "Loop", "Starts and
ends at A"; network: "Network of trails", "Most walks start at A".
"""
h = table(rec)
start, end, sh = h.get("start", ""), h.get("end", ""), h.get("shape", "")
if sh == "loop":
return ("Loop", f"Starts and ends at {start}" if start else "Starts and ends at the same place")
if sh == "network":
return ("Network of trails", f"Usual start: {start}" if start else "Several ways to start and end")
if start and end:
return ("Start and end", (start, end))
if start:
return ("Start", start)
if end:
return ("End", end)
return None
def sources(rec):
return [s for s in table(rec).get("source", []) if isinstance(s, dict)]
+319 -217
View File
@@ -1,22 +1,23 @@
"""The home page: what the site is, the overview map, and the trail finder with every record.
"""The home page: the catalogue. Search, the filters, and the trails as a list and on a map.
The list of records (results(), entry()) is shared with the region pages and
the routes page, so every list of records on the site looks and reads the same.
The list (results(), entry()) is shared with the place pages and the lists, so
every list of trails on the site looks and reads the same. The filters are the
attributes in olt/facets.py, under the same names the trail pages use.
"""
import collections
import math
import re
from . import common, words
from . import browse, common, elevation, facets, hike, words
from .markup import Markup, esc
# Length range choices (km) for the filters. length_steps() adds a top step
# above the longest record, so a chosen upper bound can always reach every record.
# above the longest trail, so a chosen upper bound can always reach every trail.
LENGTH_STEPS = (60, 80, 100, 150, 200, 300, 500, 1000, 2000, 4000, 8000)
def length_steps(records):
"""LENGTH_STEPS plus a round step at or above the longest record, when that is longer."""
"""LENGTH_STEPS plus a round step at or above the longest trail, when that is longer."""
longest = max((r["length_km"] for r in records), default=0)
steps = list(LENGTH_STEPS)
if longest > steps[-1]:
@@ -26,27 +27,31 @@ def length_steps(records):
def counts(records):
"""Counts for the filters. A record counts under each country it touches (its own
country and its regions' countries) and under each of its regions, as on /regions/;
a Canada-wide record counts under "region:CA-*", not under each province."""
"""Counts for the filter options: each Where value, Time band, month, terrain, Kind,
Walking, Shape and GPX status, as the filter would find them."""
c = collections.Counter()
for r in records:
c["total"] += 1
c[common.kind(r)] += 1
c["line" if common.has_line(r) else "record_only"] += 1
if common.is_route(r):
c["route_line" if common.has_line(r) else "route_record_only"] += 1
c["policy:" + common.policy(r)] += 1
c["tier:" + r.get("tier", "")] += 1
for country in common.countries(r):
c["country:" + country] += 1
for key in set(words.region_key(code, r["country"]) for code in r.get("regions", [])):
c["region:" + key] += 1
for tok in facets.where_tokens(r):
c["where:" + tok] += 1
c["time:" + facets.time_band(r)] += 1
for m in facets.months(r):
c[f"month:{m}"] += 1
for t in facets.terrain(r):
c["terrain:" + t] += 1
c["kind:" + facets.kind(r)] += 1
if facets.walking(r):
c["walking:" + facets.walking(r)] += 1
if facets.shape(r):
c["shape:" + facets.shape(r)] += 1
c["gpx:" + facets.gpx(r)] += 1
if facets.gpx_here(r):
c["gpx_here"] += 1
return c
def overview_bbox(records):
"""data-bbox attribute: the extent of every line, so the map opens on it before the data loads."""
"""data-bbox attribute: the extent of every track, so the map opens on it before the data loads."""
boxes = [r["derived"]["bbox"] for r in records if r["derived"].get("bbox")]
if not boxes:
return ""
@@ -58,61 +63,95 @@ def sort_name(rec):
return re.sub(r"^The ", "", rec["name"]).lower()
def entry(rec, *, level=3, extra=""):
"""One record in a list. Its data-* attributes drive the filters in app.js.
# A row ------------------------------------------------------------------------
level: the heading level of the record's name. extra: HTML placed last in the row.
def entry_desc(rec):
"""The one-line description of a row: the [hike] summary's first sentence, else
the trail's designation (an official trail) or nothing (a route says who made it)."""
one = hike.one_line(rec)
if one:
return one
if facets.kind(rec) == "route":
return ""
return rec.get("designation", "")
def where_html(rec):
"""The states and provinces of a row, each linked to its place page, and the country."""
parts = []
for key in facets.place_keys(rec):
name = facets.place_name(key)
text = esc(name) if key == facets.ACROSS_CANADA else \
Markup(f'<abbr title="{esc(name)}">{esc(key.split("-", 1)[1])}</abbr>')
parts.append(f'<a href="{esc(facets.place_path(key))}">{text}</a>')
country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec))
return Markup(" ".join(parts) + f' <span aria-hidden="true">&middot;</span> {esc(country)}')
def gpx_cell(rec):
status = facets.gpx(rec)
route = facets.kind(rec) == "route"
if facets.gpx_here(rec):
swatch = common.SWATCH_ROUTE if route else common.SWATCH_LINE
partial = (f'<p class="entry__partial">{esc(common.partial_short_text(rec))}</p>'
if common.line_differs(rec) else "")
return (f'<span class="line__status">{swatch}{esc(facets.GPX_SHORT[status])}</span>'
f'<span class="line__detail">GPX and GeoJSON</span>{partial}')
return f'<span class="line__status">{common.SWATCH_NONE}{esc(facets.GPX_SHORT[status])}</span>'
def entry(rec, *, level=3, extra="", routes_list=False):
"""One trail in a list. Its data-* attributes drive the filters in app.js.
level: the heading level of the trail's name. extra: HTML placed last in the row.
routes_list: the Routes list, whose "By <author>" headings already say what the
row's Route badge and "Route by" line would repeat; both are left out there.
"""
route = common.is_route(rec)
if route:
r = rec["route"]
desc = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "")
elif rec.get("tier") == "national" and common.designated_year(rec):
desc = "Designated " + common.designated_year(rec)
else:
desc = rec.get("designation", "")
where = Markup(f'{common.regions_html(rec, linked=True)} <span aria-hidden="true">&middot;</span> '
f'{esc(words.COUNTRIES.get(rec["country"], rec["country"]))}')
policy = common.policy_chip(common.policy(rec)) if route else ""
partial = common.line_differs(rec)
if common.has_line(rec):
partial_note = (f'<p class="entry__partial">{esc(common.partial_short_text(rec))}</p>'
if partial else "")
line = (f'<span class="line__status">{common.SWATCH_ROUTE if route else common.SWATCH_LINE}Track{policy}</span>'
f'{partial_note}'
f'<span class="line__detail">GeoJSON, GPX</span>'
f'<span class="line__detail">{esc(common.short_source(rec))} &middot; {esc(common.licence_label(rec))}</span>')
note = ""
else:
line = f'<span class="line__status">{common.SWATCH_NONE}Record only{policy}</span>'
note = (f'\n <p class="entry__note"><span class="vh">Why there is no track: </span>'
f'{esc(common.absent_reason_short(rec))}</p>')
regions = " ".join(words.region_key(c, rec["country"]) for c in rec.get("regions", []))
search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"]]
+ ([rec["route"]["creator"]] if route else [])).lower()
route = facets.kind(rec) == "route"
lo, hi, est = facets.time_days(rec)
search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"], facets.author(rec)]).lower()
abbr_cls = "entry__abbr" if common.shield_url(rec) else "entry__abbr vh"
data = (f' data-id="{esc(rec["id"])}" data-country="{esc(rec["country"])}"'
f' data-countries="{esc(" ".join(common.countries(rec)))}" data-regions="{esc(regions)}"'
f' data-km="{rec["length_km"]}" data-kind="{esc(common.kind(rec))}"'
f' data-line="{"yes" if common.has_line(rec) else "no"}"{' data-partial="yes"' if partial else ""}'
f' data-tier="{esc(rec.get("tier", ""))}"'
f' data-policy="{esc(common.policy(rec))}" data-name="{esc(sort_name(rec))}" data-search="{esc(search)}"')
elev = elevation.get(rec)
# A climb worked out from a track that covers only part of the trail, or more
# than the trail, would mislead in a list; the trail's own page gives it with
# its caveat.
if elev and elevation.coverage_kind(elev):
elev = None
data = {
"id": rec["id"], "where": " ".join(facets.where_tokens(rec)), "km": rec["length_km"],
"climb": elev["ascent_m"] if elev else "",
"days": hi, "time": facets.time_band(rec), "months": " ".join(map(str, facets.months(rec))),
"terrain": " ".join(facets.terrain(rec)), "kind": facets.kind(rec), "walking": facets.walking(rec),
"shape": facets.shape(rec), "gpx": facets.gpx(rec), "name": sort_name(rec), "search": search.strip(),
}
attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items())
if common.line_differs(rec):
attrs += ' data-partial="yes"'
h = f"h{level}"
return f"""<li class="entry"{data}>
tag_html = common.badges(rec, route_tag=not routes_list)
kicker = f'\n <p class="entry__kicker">{tag_html}</p>' if tag_html else ""
by = f'\n <p class="entry__by">{esc(facets.route_by(rec))}</p>' if route and not routes_list else ""
desc = entry_desc(rec)
desc_html = f'\n <p class="entry__desc">{esc(desc)}</p>' if desc else ""
time_html = esc(facets.time_text(rec)) + (' <small class="entry__est">estimate</small>' if est else "")
climb_html = (f'\n <div class="entry__climb"><dt>Climb</dt><dd>{words.elevation(elev["ascent_m"], "stack")}'
f'<small class="entry__est">computed</small></dd></div>') if elev else ""
return f"""<li class="entry"{attrs}>
{common.plate(rec)}
<div class="entry__body">
<p class="entry__kicker">{common.tags(rec, with_policy=False)}</p>
<{h} class="entry__name"><a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a> <span class="{abbr_cls}">{esc(rec.get("short_name", ""))}</span></{h}>
<p class="entry__desc">{esc(desc)}</p>
<p class="entry__where">{where}</p>
<div class="entry__body">{kicker}
<{h} class="entry__name"><a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a> <span class="{abbr_cls}">{esc(rec.get("short_name", ""))}</span></{h}>{by}{desc_html}
<p class="entry__where">{where_html(rec)}</p>
</div>
<dl class="entry__facts">
<div class="entry__length"><dt>Length</dt><dd>{words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}<span class="loglen" style="--km: {rec["length_km"]}" aria-hidden="true"></span></dd></div>
<div class="entry__line"><dt>Track</dt><dd class="line line--{"yes" if common.has_line(rec) else "no"}">{line}</dd></div>
</dl>{note}{extra}
<div class="entry__time"><dt>Time</dt><dd>{time_html}</dd></div>
<div class="entry__line"><dt>GPX</dt><dd class="line line--{"yes" if facets.gpx_here(rec) else "no"}">{gpx_cell(rec)}</dd></div>{climb_html}
</dl>{extra}
</li>"""
# The filters ------------------------------------------------------------------
def _length_options(steps, selected_any_last):
opts = [f'<option value="{km}">{km:,} km &middot; {words.fmt_int(words.km_to_mi(km))} mi</option>'
for km in steps]
@@ -121,97 +160,138 @@ def _length_options(steps, selected_any_last):
return '<option value="">Any</option>' + "".join(opts[:-1])
def region_options(c):
"""The region filter: each state, province and territory a record names, with the
count its /regions/ page shows; the Canada-wide records under their own option."""
groups = []
for country, table in (("US", words.US_STATES), ("CA", words.CA_PROVINCES)):
opts = []
if country == "CA" and c["region:CA-*"]:
key = words.region_key(words.ALL_CANADA, "CA")
opts.append(f'<option value="{esc(key)}">{esc(words.region_name(words.ALL_CANADA))} '
f'({c["region:" + key]})</option>')
for code, name in sorted(table.items(), key=lambda kv: kv[1]):
n = c[f"region:{country}-{code}"]
if n:
opts.append(f'<option value="{country}-{code}">{esc(name)} ({n})</option>')
groups.append(f'<optgroup label="{esc(words.COUNTRIES[country])}" data-country="{country}">{"".join(opts)}</optgroup>')
return "".join(groups)
def where_options(c):
"""The Where filter: the two countries, then each place group with its states and provinces."""
opts = [f'<option value="">Anywhere ({c["total"]})</option>']
for code in ("US", "CA"):
if c["where:" + code]:
opts.append(f'<option value="{code}">{esc(words.COUNTRIES[code])} ({c["where:" + code]})</option>')
for g, name, keys in facets.PLACE_GROUPS:
if not c["where:g:" + g]:
continue
inner = [f'<option value="g:{g}">All of {esc(name)} ({c["where:g:" + g]})</option>']
for key in sorted(keys, key=facets.place_name):
if c["where:" + key]:
inner.append(f'<option value="{key}">{esc(facets.place_name(key))} ({c["where:" + key]})</option>')
opts.append(f'<optgroup label="{esc(name)}">{"".join(inner)}</optgroup>')
if c["where:" + facets.ACROSS_CANADA]:
opts.append(f'<option value="{facets.ACROSS_CANADA}">{facets.ACROSS_CANADA_NAME} '
f'({c["where:" + facets.ACROSS_CANADA]})</option>')
return "".join(opts)
def finder_form(c, steps=LENGTH_STEPS):
tier_opts = "".join(
f'<option value="{t}">{esc(words.label(words.TIERS, t))} ({c["tier:" + t]})</option>'
for t in ("national", "regional", "short", "deferred", "candidate") if c["tier:" + t])
policy_opts = "".join(
f'<option value="{p}">{esc(words.label(words.POLICIES, p))}: {esc(words.meaning(words.POLICIES, p).lower())} ({c["policy:" + p]})</option>'
for p in ("open", "sold", "withheld", "unclear") if c["policy:" + p])
def _checks(name, items, c, prefix, hints=None):
"""Checkboxes for a multi-choice facet: (value, label) items with their counts."""
out = []
for value, label in items:
n = c[f"{prefix}:{value}"]
if not n:
continue
hint = f'<span class="check__hint">{esc(hints[value])}</span>' if hints and hints.get(value) else ""
out.append(f'<label class="check"><input type="checkbox" name="{name}" value="{esc(value)}">'
f'<span class="check__text">{esc(label)} <span class="check__count">{n}</span></span>{hint}</label>')
return "".join(out)
def _missing(records, key):
"""The note under an optional facet: how many trails it leaves out while it is in use."""
_, without = facets.coverage(records, key)
if not without:
return ""
return (f'<p class="field__hint filter-missing" data-missing="{key}" hidden>'
f'{esc(facets.missing_text(without, key))} They are left out while this filter is on.</p>')
def finder_form(records, c=None, steps=None):
"""Search and the first-rank filters in view; Walking, Shape and GPX behind "More"."""
c = c or counts(records)
steps = steps or length_steps(records)
first, more = [], []
first.append(f"""<div class="field">
<label class="field__label" for="where">{facets.WHERE}</label>
<select class="select" id="where" name="where">{where_options(c)}</select>
</div>""")
first.append(f"""<fieldset class="field">
<legend>{facets.LENGTH}</legend>
<div class="range">
<label class="vh" for="min">Shortest length</label>
<select class="select" id="min" name="min" data-length-options>{_length_options(steps, False)}</select>
<span class="range__to" aria-hidden="true">to</span>
<label class="vh" for="max">Longest length</label>
<select class="select" id="max" name="max" data-length-options>{_length_options(steps, True)}</select>
</div>
<p class="field__hint" id="len-hint" aria-live="polite">Any length.</p>
</fieldset>""")
first.append(f"""<fieldset class="field">
<legend>{facets.TIME}</legend>
<div class="pills">{_checks("time", [(k, label) for k, label, _ in facets.TIME_BANDS], c, "time")}</div>
<p class="field__hint">To walk it all. Where no source says, it is estimated from the length.</p>
</fieldset>""")
if facets.offered(records, "season"):
month_opts = "".join(f'<option value="{i}">{esc(m)} ({c[f"month:{i}"]})</option>'
for i, m in enumerate(facets.MONTHS, 1))
first.append(f"""<div class="field">
<label class="field__label" for="month">{facets.SEASON}</label>
<select class="select" id="month" name="month"><option value="">Any month</option>{month_opts}</select>
<p class="field__hint">Trails usually walked in that month.</p>
{_missing(records, "season")}
</div>""")
if facets.offered(records, "terrain"):
first.append(f"""<fieldset class="field">
<legend>{facets.TERRAIN}</legend>
<div class="pills">{_checks("terrain", facets.TERRAIN_VALUES.items(), c, "terrain")}</div>
{_missing(records, "terrain")}
</fieldset>""")
first.append(f"""<fieldset class="field">
<legend>{facets.KIND}</legend>
<div class="seg">
<label><input type="radio" name="kind" value="" checked><span>Any</span></label>
<label><input type="radio" name="kind" value="trail"><span>Official trails ({c["kind:trail"]})</span></label>
<label><input type="radio" name="kind" value="route"><span>Routes ({c["kind:route"]})</span></label>
</div>
<p class="field__hint"><a href="/routes/">What is a route?</a></p>
</fieldset>""")
if facets.offered(records, "walking"):
more.append(f"""<fieldset class="field">
<legend>{facets.WALKING}</legend>
{_checks("walking", facets.WALKING_VALUES.items(), c, "walking", facets.WALKING_HINT)}
{_missing(records, "walking")}
</fieldset>""")
if facets.offered(records, "shape"):
more.append(f"""<fieldset class="field">
<legend>{facets.SHAPE}</legend>
{_checks("shape", facets.SHAPES.items(), c, "shape")}
{_missing(records, "shape")}
</fieldset>""")
more.append(f"""<fieldset class="field">
<legend>{facets.GPX}</legend>
{_checks("gpx", facets.GPX_STATUS.items(), c, "gpx")}
</fieldset>""")
return f"""<form class="filters" id="finder-form" role="search" aria-label="Find a trail">
<div class="filters__search field">
<label class="field__label" for="q">Search</label>
<input class="input" id="q" name="q" type="search" placeholder="Name, abbreviation or creator" autocomplete="off" spellcheck="false">
<input class="input" id="q" name="q" type="search" placeholder="Name, abbreviation or author of a route" autocomplete="off" spellcheck="false">
</div>
<div class="field">
<label class="check">
<input type="checkbox" name="line">
<span class="check__text">Has a downloadable track <span class="check__count">{c["line"]}</span></span>
<span class="check__hint">GeoJSON and GPX. The other {c["record_only"]} are records only.</span>
</label>
</div>
<details class="filters__more">
<summary>Filters <span class="filters__active"></span></summary>
<div class="filters__form">
<fieldset class="field">
<legend>Country</legend>
<div class="seg">
<label><input type="radio" name="country" value="all" checked><span>Both ({c["total"]})</span></label>
<label><input type="radio" name="country" value="US"><span>United States ({c["country:US"]})</span></label>
<label><input type="radio" name="country" value="CA"><span>Canada ({c["country:CA"]})</span></label>
</div>
<p class="field__hint">A record that crosses the border counts under both.</p>
</fieldset>
<div class="field">
<label class="field__label" for="region">State, province or territory</label>
<select class="select" id="region" name="region"><option value="">Any</option>{region_options(c)}</select>
</div>
<fieldset class="field field--wide">
<legend>Length</legend>
<div class="range">
<label class="vh" for="min">Shortest length</label>
<select class="select" id="min" name="min" data-length-options>{_length_options(steps, False)}</select>
<span class="range__to" aria-hidden="true">to</span>
<label class="vh" for="max">Longest length</label>
<select class="select" id="max" name="max" data-length-options>{_length_options(steps, True)}</select>
</div>
<p class="field__hint" id="len-hint" aria-live="polite">Any length.</p>
</fieldset>
<fieldset class="field">
<legend>Kind</legend>
<label class="check">
<input type="checkbox" name="designated" checked>
<span class="check__text">Designated trails <span class="check__count">{c["designated"]}</span></span>
<span class="check__hint">Designated by a land agency or a trail association</span>
</label>
<label class="check">
<input type="checkbox" name="route" checked>
<span class="check__text">Person-defined routes <span class="check__count">{c["route"]}</span></span>
<span class="check__hint">Worked out and published by a person or a small group</span>
</label>
<label class="field__label field__label--sub" for="policy">Route track policy</label>
<select class="select" id="policy" name="policy"><option value="">Any</option>{policy_opts}</select>
</fieldset>
<div class="field">
<label class="field__label" for="tier">Tier</label>
<select class="select" id="tier" name="tier"><option value="">Any</option>{tier_opts}</select>
</div>
<div class="field field--wide">
<button class="button button--quiet" type="reset">Clear search and filters</button>
</div>
<details class="filters__panel" open>
<summary>Filters <span class="filters__count"></span></summary>
<div class="filters__first">
{"".join(first)}
</div>
</details>
<details class="filters__more">
<summary>More filters <span class="filters__active"></span></summary>
<div class="filters__form">
{"".join(more)}
</div>
</details>
<div class="field filters__reset">
<button class="button button--quiet" type="reset">Clear search and filters</button>
</div>
</form>"""
# The list ---------------------------------------------------------------------
# The length strip's ticks (style.css .loglen): 100, 1,000 and 10,000 km.
SCALE_KM = (100, 1000, 10000)
@@ -227,8 +307,10 @@ def list_head():
f'<span class="len__mi">{words.fmt_int(words.km_to_mi(km))}{mi_unit}</span></span>')
return f"""<div class="list-head" aria-hidden="true">
<span>Trail</span>
<span>Length<span class="list-head__scale">{"".join(ticks)}</span></span>
<span>Track</span>
<span>{facets.LENGTH}<span class="list-head__scale">{"".join(ticks)}</span></span>
<span>{facets.TIME}</span>
<span>{facets.GPX}</span>
<span>Climb</span>
</div>"""
@@ -245,35 +327,40 @@ SORT_SELECT = """<label class="results-sort">Sort
<option value="name">Name, A to Z</option>
<option value="long">Longest first</option>
<option value="short">Shortest first</option>
<option value="quick">Quickest first</option>
<option value="climb">Most climb first</option>
</select>
</label>"""
def key():
def key(official=True):
"""official: False on a list of routes only, which has no official trail to explain."""
first = f"<li>{common.SWATCH_LINE}Official trail with a GPX here</li>\n " if official else ""
return f"""<ul class="key" aria-label="Key to the list">
<li>{common.SWATCH_LINE}Track in the dataset</li>
<li>{common.SWATCH_NONE}Record only; the note says why</li>
<li>Route track policy:
{common.policy_chip("open")} {common.policy_chip("sold")} {common.policy_chip("withheld")} {common.policy_chip("unclear")}
</li>
{first}<li>{common.SWATCH_ROUTE}Route with a GPX here</li>
<li>{common.SWATCH_NONE}No GPX here: its page says where to get one</li>
</ul>"""
def results(recs=None, *, finder=False, groups=None):
"""The list of records, as every page shows it: div.results > head, key, list head, ol.entries.
def results(recs=None, *, finder=False, groups=None, routes_list=False):
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
finder: the home page's list, driven by the finder form (live count, sort, empty state).
groups: [(heading, records, extra_fn)] to list the records under level-3 headings
(the routes page); extra_fn(rec) gives HTML placed last in each row.
finder: the home page's list, driven by the filters (live count, sort, empty state).
groups: [(heading, trails, extra_fn)] to list the trails under level-3 headings;
extra_fn(rec) gives HTML placed last in each row.
routes_list: passed to entry() for the Routes list (see there).
"""
if groups is None:
groups = [(None, recs, None)]
total = sum(len(g[1]) for g in groups)
noun = "record" if total == 1 else "records"
shown = [r for g in groups for r in g[1]]
only_routes = bool(shown) and all(facets.kind(r) == "route" for r in shown)
noun = ("route" if only_routes else "trail") + ("" if total == 1 else "s")
lists = ""
for heading, items, extra_fn in groups:
level = 4 if heading else 3
rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "") for r in items)
rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "",
routes_list=routes_list) for r in items)
if heading:
lists += f'\n <h3 class="results__group">{heading}</h3>'
list_id = ' id="entries"' if finder else ""
@@ -284,7 +371,7 @@ def results(recs=None, *, finder=False, groups=None):
tools = SORT_SELECT + "\n " + UNITS_TOGGLE
empty = """
<div class="empty-state" id="empty-state" hidden>
<p><strong>No records match these filters.</strong></p>
<p><strong>No trails match these filters.</strong></p>
<button class="button button--quiet" type="button" data-reset>Clear search and filters</button>
</div>"""
else:
@@ -298,80 +385,95 @@ def results(recs=None, *, finder=False, groups=None):
{tools}
</div>
</div>
{key()}
{key(official=not only_routes)}
{list_head()}{lists}{empty}
</div>""")
# A map of a selection is drawn only when it has at least this many tracks.
MAP_MIN = 3
def overview_map(recs, label, *, wide=False, scope=""):
"""The map of the given trails' tracks (the overview geometry, limited to their ids
unless every trail is shown). "" when none of them has a track."""
ids = [r["id"] for r in recs if "line" in r["derived"]["files"]]
if not ids:
return Markup('<p class="note">None of these trails has a GPX here, so there is no track to draw. '
'Each trail&rsquo;s page says where to get one.</p>')
if len(ids) < MAP_MIN and scope != "all":
names = words.join_names(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>'
for r in recs if r["id"] in ids)
return Markup(f'<p class="note">Only {names} {"has" if len(ids) == 1 else "have"} a GPX here, '
'so no map of them all is drawn. Each trail&rsquo;s page says where to get a track.</p>')
ids_attr = "" if scope == "all" else f' data-ids="{esc(" ".join(ids))}"'
n = len(ids)
return Markup(f"""<figure class="mapfig{" mapfig--wide" if wide else ""}" data-map="overview" data-src="/data/overview.geojson"{ids_attr}{overview_bbox(recs)}>
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
<div class="map" role="region" aria-label="{esc(label)}">
<div class="map__fallback"></div>
<div class="map__canvas"></div>
<p class="map__status" role="status">The map needs JavaScript. The list has every trail.</p>
</div>
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
</div>
<figcaption class="mapfig__caption">
<ul class="legend" aria-label="Legend">
<li>{common.SWATCH_LINE}Official trail</li>
<li>{common.SWATCH_ROUTE}Route</li>
</ul>
<p>{n} track{"s" if n != 1 else ""}, simplified for display. Select one for its name. Each trail&rsquo;s page names its source, credit and licence. Base map: OpenFreeMap, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;OpenStreetMap contributors.</p>
</figcaption>
</figure>""")
def lists_row(records):
"""The ready-made lists, as a row of links with their counts. The terrain lists are
on /lists/; here the Terrain filter does the same work."""
items = "".join(
f'<li><a href="{esc(browse.path(lst))}">{esc(lst.title)} <span class="chips__n">{len(recs)}</span></a></li>'
for lst, recs in browse.shown(records) if not lst.key.startswith("terrain-"))
if not items:
return ""
return f"""<nav class="lists-row" aria-labelledby="lists-title">
<h2 id="lists-title" class="lists-row__title">Start from a list</h2>
<ul class="chips">{items}<li><a href="/lists/">All lists</a></li></ul>
</nav>"""
def render(records, site):
"""The home page body (HTML) for every record."""
"""The home page body (HTML)."""
c = counts(records)
recs = sorted(records, key=sort_name)
total = c["total"]
lede = (f"A record for each of {total} long trails and routes, as a rule 50 miles (80&nbsp;km) or more: "
"what it is, how long it is, who publishes it, and on what terms its track may be passed on. "
"Where the terms allow, download the track as GPX or GeoJSON.")
lede = (f"{total} long-distance trails in the United States and Canada. Narrow them by where they are, "
f"how long they take, when to walk them and what the country is like. "
f"{c['gpx_here']} have a GPX to download.")
contribute = ""
if site.repo_url:
contribute = (f'<p class="hero__caveat">Something wrong, or a trail missing? '
contribute = (f'<p class="finder__foot">Something wrong, or a trail missing? '
f'<a href="{esc(site.correction_url())}">Report a problem</a> or '
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a>; '
f'the records are text files <a href="{esc(site.repo_url)}">anyone can fix or add to</a>.</p>')
return f"""<section class="hero" aria-labelledby="hero-title">
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a>.</p>')
return f"""<section class="hero hero--short" aria-labelledby="hero-title">
<div class="container hero__inner">
<p class="kicker">A public dataset &middot; United States and Canada</p>
<h1 id="hero-title">{esc(site.tagline)}</h1>
<h1 id="hero-title">Find a long trail</h1>
<p class="hero__lede">{lede}</p>
<p class="hero__caveat">This is a dataset, not a navigation product. Tracks vary in quality, some trails are unfinished, and some records have no track at all; each of those says why.</p>
{contribute}
<p><a class="button button--primary hero__cta" href="#q">Find a trail</a></p>
<div class="hero__counts">
<dl class="tally">
<div><dt>Records</dt><dd>{total}</dd></div>
<div><dt><a href="/?kind=designated">Designated trails</a></dt><dd>{c["designated"]}</dd></div>
<div><dt><a href="/?kind=route">Person-defined routes</a></dt><dd>{c["route"]}</dd></div>
<div><dt>{common.SWATCH_LINE}<a href="/?line=1">With a track</a></dt><dd>{c["line"]}</dd></div>
<div><dt>{common.SWATCH_NONE}Records only</dt><dd>{c["record_only"]}</dd></div>
</dl>
<div class="ratio" aria-hidden="true"><span class="ratio__line" style="--n: {c["line"]}"></span><span class="ratio__none" style="--n: {c["record_only"]}"></span></div>
</div>
{lists_row(records)}
</div>
</section>
<section class="section" aria-labelledby="map-title">
<div class="container">
<div class="section-head">
<h2 id="map-title">Every track in the dataset</h2>
<p>{c["line"]} tracks, simplified for display. Select a trail on the map for its name.</p>
</div>
<figure class="mapfig" data-map="overview" data-src="/data/overview.geojson"{overview_bbox(records)}>
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
<div class="map" role="region" aria-label="Map of every track in the dataset">
<div class="map__fallback"></div>
<div class="map__canvas"></div>
<p class="map__status" role="status">The map needs JavaScript. The list below has every record.</p>
</div>
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
</div>
<figcaption class="mapfig__caption">
<ul class="legend" aria-label="Legend">
<li>{common.SWATCH_LINE}Designated trail</li>
<li>{common.SWATCH_ROUTE}Person-defined route</li>
</ul>
<p>Tracks are simplified to about 750&nbsp;m here; each keeps the credit and licence named on its page. Base map: OpenFreeMap, &copy;&nbsp;OpenMapTiles, data &copy;&nbsp;OpenStreetMap contributors.</p>
</figcaption>
</figure>
</div>
</section>
<section class="section" id="finder" aria-labelledby="finder-title">
<section class="section section--finder" id="finder" aria-labelledby="finder-title">
<div class="container finder__grid">
<div class="finder__head section-head">
<h2 id="finder-title">Find a trail</h2>
<p>Search, then narrow by country, region, length, kind and track</p>
<h2 class="vh" id="finder-title">Every trail</h2>
{finder_form(records, c, length_steps(records))}
<div class="finder__main">
{overview_map(records, "Map of the trails the filters leave", wide=True, scope="all")}
{results(recs, finder=True)}
</div>
<div class="finder__notes">
<p class="finder__foot">Not for navigation: tracks vary in quality and some trails are unfinished. Check each trail&rsquo;s own maps before you go.</p>
{contribute}
</div>
{finder_form(c, length_steps(records))}
{results(recs, finder=True)}
</div>
</section>"""
+29 -24
View File
@@ -5,9 +5,9 @@ To add a page (see also docs in pages.py):
from olt.layout import layout, page_head, write_page
from olt.markup import esc
body = page_head("Regions", kicker="Browse", lede="Trails by state, province and territory.")
body = page_head("Places", lede="Trails by state and province.")
body += f'<div class="container prose">...{esc(some_text)}...</div>'
html = layout("Regions", body, path="/regions/", description="Long trails by region.")
html = layout("Places", body, path="/regions/", description="Long trails by place.")
write_page(out_dir, "/regions/", html)
`path` is the page's own site path; it sets the canonical link (when
@@ -23,13 +23,14 @@ from .markup import Markup, attrs, esc, json_block
NAV = (
("Trails", "/"),
("Regions", "/regions/"),
("Routes", "/routes/"),
("Sources", "/sources/"),
("Logos", "/logos/"),
("Places", "/regions/"),
("About", "/about/"),
("Data", "/data/"),
)
# Pages with no header item of their own, and the item they sit under. The
# lists (Routes among them) are part of Trails; the dataset pages are part of
# About and are linked from the About hub and the footer.
NAV_PARENT = {"/trails/": "/", "/lists/": "/", "/routes/": "/",
"/sources/": "/about/", "/logos/": "/about/", "/data/": "/about/"}
FONT_PRELOADS = (
"/assets/fonts/source-serif-4-latin.woff2",
@@ -41,9 +42,11 @@ MAPLIBRE_JS = "/assets/vendor/maplibre-gl/maplibre-gl.js"
def _current(path, href):
"""True when the nav item href is the section the page at path belongs to."""
if href == "/":
return path == "/" or path.startswith("/trails/")
return path.startswith(href)
if href == "/" and path == "/":
return True
if any(path.startswith(p) and parent == href for p, parent in NAV_PARENT.items()):
return True
return href != "/" and path.startswith(href)
def header(path, site):
@@ -62,30 +65,32 @@ def header(path, site):
def footer(site):
report = ""
if site.repo_url:
report = (f'<li><a href="{esc(site.correction_url())}">Report an error in a record</a></li>'
report = (f'<li><a href="{esc(site.correction_url())}">Report a problem</a></li>'
f'<li><a href="{esc(site.new_trail_url)}">Suggest a trail</a></li>'
f'<li><a href="{esc(site.repo_url)}">Fix or add a trail</a></li>')
return Markup(f"""<footer class="site-footer">
<div class="container site-footer__grid">
<div class="site-footer__about">
<a class="wordmark" href="/"><span class="wordmark__blaze" aria-hidden="true"></span>{esc(site.name)}</a>
<p>A dataset, not a navigation product: tracks vary in quality, some trails are unfinished, and some records have no track at all. Check a trail&rsquo;s own record before using its track.</p>
<p>The records are public domain (CC0-1.0). Each track keeps the terms of its source, named on its page. Tracks from OpenStreetMap are &copy;&nbsp;OpenStreetMap contributors, under the ODbL. Logos belong to their holders and are shown only to identify each trail.</p>
<p>Not for navigation: tracks vary in quality, some trails are unfinished, and some have no GPX here. Check a trail&rsquo;s own maps before you go.</p>
<p>The trail data is public domain (CC0-1.0). Each track keeps the terms of its source, named on its page. Tracks from OpenStreetMap are &copy;&nbsp;OpenStreetMap contributors, under the ODbL. Logos belong to their holders and are shown only to identify each trail.</p>
</div>
<nav aria-labelledby="footer-data">
<h2 id="footer-data">Data</h2>
<nav aria-labelledby="footer-browse">
<h2 id="footer-browse">Trails</h2>
<ul>
<li><a href="/data/">About the data and downloads</a></li>
<li><a href="/data/trails.csv">trails.csv</a>: one row per trail</li>
<li><a href="/data/index.geojson">index.geojson</a>: every track, simplified</li>
<li><a href="/sources/">Sources and their terms</a></li>
<li><a href="/">Every trail</a></li>
<li><a href="/regions/">Places</a></li>
<li><a href="/lists/">Lists</a></li>
<li><a href="/routes/">Routes</a></li>
</ul>
</nav>
<nav aria-labelledby="footer-project">
<h2 id="footer-project">Project</h2>
<h2 id="footer-project">About</h2>
<ul>
<li><a href="/about/">About {esc(site.name)}</a></li>
<li><a href="/logos/">Logos and removal requests</a></li>
<li><a href="/data/">Data and downloads</a></li>
<li><a href="/sources/">Sources and their terms</a></li>
<li><a href="/logos/">Logos</a></li>
{report}
</ul>
</nav>
@@ -99,10 +104,10 @@ def footer(site):
</div>
</fieldset>
<fieldset class="field">
<legend>Lengths</legend>
<legend>Units</legend>
<div class="seg">
<label><input type="radio" name="units" value="km" checked><span>km first</span></label>
<label><input type="radio" name="units" value="mi"><span>miles first</span></label>
<label><input type="radio" name="units" value="km" checked><span>km and m first</span></label>
<label><input type="radio" name="units" value="mi"><span>mi and ft first</span></label>
</div>
</fieldset>
</div>
+24 -10
View File
@@ -8,6 +8,9 @@ writes:
/trails/<id>/index.html one page per record
/trails/<id>/trail.toml the raw record; release.txt beside it where the trail has one
/trails/<id>/shield-thumb.png the list-size copy of a PNG logo (olt/thumbs.py)
/regions/, /regions/<slug>/ Places: the hub and one page per state or province
/lists/, /lists/<key>/ the lists shown today (olt/browse.py); /routes/ is the Routes list
/about/ and the pages under it: /data/, /data/schema/, /data/changelog/, /sources/, /logos/
/404.html not found
Adding a page elsewhere (regions, sources, ...): build its body as HTML,
@@ -18,7 +21,7 @@ import json
import os
import shutil
from . import docs, home, layout, regions, seo, site as site_settings, thumbs, trail
from . import browse, docs, home, layout, regions, seo, site as site_settings, thumbs, trail
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ASSETS_DIR = os.path.join(WEB_DIR, "assets")
@@ -55,14 +58,14 @@ def copy_record_files(rec, out_dir, repo_root):
def not_found_page(site):
body = layout.page_head("Page not found", kicker="404",
lede="There is no page at this address. Search the trails and routes by name instead.")
lede="There is no page at this address. Search the trails by name instead.")
body += """<div class="container section">
<form class="notfound-search" action="/" method="get" role="search">
<label class="field__label" for="notfound-q">Search the trails and routes</label>
<input class="input" id="notfound-q" name="q" type="search" placeholder="Name, abbreviation or creator" autocomplete="off" spellcheck="false">
<label class="field__label" for="notfound-q">Search the trails</label>
<input class="input" id="notfound-q" name="q" type="search" placeholder="Name, abbreviation or author of a route" autocomplete="off" spellcheck="false">
<button class="button button--primary" type="submit">Search</button>
</form>
<p class="prose"><a href="/">Find a trail</a> on the home page, or browse <a href="/regions/">by region</a>.</p>
<p class="prose"><a href="/">Find a trail</a> on the home page, or browse by <a href="/regions/">place</a>.</p>
</div>"""
return layout.layout("Page not found", body, path="/404.html", site=site)
@@ -78,7 +81,7 @@ def render_site(records, out_dir, repo_root, site=None):
for rec in records:
copy_record_files(rec, out_dir, repo_root)
thumbs.prepare(rec, out_dir, repo_root)
title, description, body, needs_map = trail.render(rec, site)
title, description, body, needs_map = trail.render(rec, site, records)
path = f"/trails/{rec['id']}/"
layout.write_page(out_dir, path, layout.layout(title, body, path=path, description=description,
maps=needs_map, site=site))
@@ -104,8 +107,19 @@ def render_site(records, out_dir, repo_root, site=None):
path = f"/regions/{slug}/"
region_paths.append(path)
add(path, t, d, b, maps=needs_map)
t, d, b = regions.routes_page(records, site, repo_root)
add("/routes/", t, d, b)
list_paths = []
shown = browse.shown(records)
for lst, recs in shown:
if lst.key == "routes":
continue # /routes/ below, built whether or not the list is shown
t, d, b, needs_map = regions.list_page(lst, recs, len(records), site)
path = browse.path(lst)
list_paths.append(path)
add(path, t, d, b, maps=needs_map)
t, d, b = regions.lists_index_page(records, site)
add("/lists/", t, d, b)
t, d, b, needs_map = regions.routes_page(records, site, repo_root)
add("/routes/", t, d, b, maps=needs_map)
t, d, b = docs.sources_page(records, site, repo_root)
add("/sources/", t, d, b)
t, d, b = docs.logos_page(records, site, repo_root)
@@ -119,6 +133,6 @@ def render_site(records, out_dir, repo_root, site=None):
t, d, b = docs.changelog_page(site, repo_root)
add("/data/changelog/", t, d, b)
docs.copy_licences(out_dir, repo_root)
seo.write_seo_files(out_dir, seo.all_paths(records, region_paths), site)
print(f"pages written {pages}: {len(records)} trail pages, home, 404, regions, routes, docs")
seo.write_seo_files(out_dir, seo.all_paths(records, region_paths + ["/lists/"] + list_paths), site)
print(f"pages written {pages}: {len(records)} trail pages, home, 404, places, lists, about")
return pages
+3
View File
@@ -2,6 +2,8 @@
import os
import tomllib
from . import elevation
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SHIELD_NAMES = ("shield.svg", "shield.png")
@@ -50,6 +52,7 @@ def load_record(root, tid):
"has_line": bool(rec.get("source", {}).get("line_file")),
"length_mi": int(round(length_km / 1.609344)),
"files": find_files(root, tid, rec),
"elevation": elevation.load_file(root, tid),
"status": trail_status(rec),
}
return rec
+166 -161
View File
@@ -1,180 +1,137 @@
"""Region pages (/regions/, /regions/<slug>/) and the routes page (/routes/).
"""Places (/regions/, /regions/<state or province>/), lists (/lists/, /lists/<key>/) and
the Routes list (/routes/).
Both list records with home.results(), the same list the home page shows.
Every page lists trails with home.results(), the same rows the home page shows.
The section is called Places; its pages keep their /regions/ URLs.
"""
import collections
from . import common, docs, home, words
from . import browse, common, facets, home, words
from .markup import Markup, esc
# The /regions/ anchor and the finder's region key for records that name all of Canada.
CANADA_WIDE_ID = "canada-wide"
CANADA_WIDE_KEY = words.region_key(words.ALL_CANADA, "CA") # "CA-*"
def region_country(code):
return words.region_country(code) if code != words.ALL_CANADA else ""
def region_slug(code, fallback_country=""):
return words.region_key(code, region_country(code) or fallback_country).lower()
def region_path(code, fallback_country=""):
return f"/regions/{region_slug(code, fallback_country)}/"
def collect_regions(records):
"""slug -> {code, country, name, records}; plus Canada-wide records separately."""
"""slug -> {key, code, country, name, group, records} for every state and province a
trail names; plus the trails that name all of Canada, separately."""
by_slug = {}
canada_wide = []
across = []
for r in records:
for code in r.get("regions", []):
if code == words.ALL_CANADA:
canada_wide.append(r)
for key in facets.place_keys(r):
if key == facets.ACROSS_CANADA:
across.append(r)
continue
country = region_country(code) or r["country"]
slug = region_slug(code, r["country"])
info = by_slug.setdefault(slug, {"code": code, "country": country,
"name": words.region_name(code), "records": []})
slug = key.lower()
country, code = key.split("-", 1)
info = by_slug.setdefault(slug, {"key": key, "code": code, "country": country,
"name": facets.place_name(key),
"group": facets.GROUP_OF.get(key, ""), "records": []})
if all(x["id"] != r["id"] for x in info["records"]):
info["records"].append(r)
for info in by_slug.values():
info["records"].sort(key=home.sort_name)
canada_wide.sort(key=home.sort_name)
return by_slug, canada_wide
across.sort(key=home.sort_name)
return by_slug, across
def country_records(records, country):
"""Every record that touches a country: listed on one of its region pages, or Canada-wide."""
return [r for r in records if country in common.countries(r)]
def group_records(records, group):
return [r for r in records if group in facets.place_groups(r)]
def _bbox_attr(recs):
boxes = [r["derived"]["bbox"] for r in recs if r["derived"].get("bbox")]
if not boxes:
return ""
box = [min(b[0] for b in boxes), min(b[1] for b in boxes),
max(b[2] for b in boxes), max(b[3] for b in boxes)]
return f' data-bbox="{",".join(f"{v:.4f}" for v in box)}"'
def _gpx_count(recs):
return sum(1 for r in recs if facets.gpx_here(r))
def _region_map(recs, title):
ids = [r["id"] for r in recs if "line" in r["derived"]["files"]]
if not ids:
return ('<p class="note">No downloadable track in this region yet, so there is '
'nothing to draw. The records below say why.</p>')
return f"""<figure class="mapfig" data-map="overview" data-src="/data/overview.geojson" data-ids="{esc(" ".join(ids))}"{_bbox_attr(recs)}>
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
<div class="map" role="region" aria-label="Map of tracks in {esc(title)}">
<div class="map__fallback"></div><div class="map__canvas"></div>
<p class="map__status" role="status">The map needs JavaScript. The list below has every record.</p>
</div>
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
</div>
<figcaption class="mapfig__caption">
<ul class="legend" aria-label="Legend"><li>{common.SWATCH_LINE}Designated trail</li>
<li>{common.SWATCH_ROUTE}Person-defined route</li></ul>
<p>{len(ids)} track{"s" if len(ids) != 1 else ""} in this region, simplified for display. Select a trail on the map for its name.</p>
</figcaption>
</figure>"""
def _plural(n, word="trail"):
return f"{n} {word}{'' if n == 1 else 's'}"
def regions_index_page(records, site):
by_slug, canada_wide = collect_regions(records)
"""(title, description, body) for /regions/: the Places hub."""
by_slug, across = collect_regions(records)
blocks = ""
tally = '<div><dt>Records</dt><dd>' + str(len(records)) + '</dd></div>'
for country in ("US", "CA"):
n_country = len(country_records(records, country))
tally += (f'<div><dt><a href="#{esc(country.lower())}">{esc(words.COUNTRIES[country])}</a></dt>'
f'<dd data-country-count="{esc(country)}">{n_country}</dd></div>')
infos = sorted((i for i in by_slug.values() if i["country"] == country),
key=lambda i: i["name"].lower())
rows = ""
for info in infos:
lines = sum(1 for r in info["records"] if common.has_line(r))
rows += (f'<tr><td><a href="{esc(region_path(info["code"], country))}">{esc(info["name"])}</a> '
f'<code class="raw">{esc(info["code"])}</code></td>'
f'<td class="num">{len(info["records"])}</td><td class="num">{lines}</td></tr>')
extra = ""
if country == "CA" and canada_wide:
links = ", ".join(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>' for r in canada_wide)
extra = (f'<div class="doc-block" id="{CANADA_WIDE_ID}"><h3>All provinces and territories</h3>'
f'<p class="prose">These records name <em>all provinces and territories</em> rather than '
f'one province, so they have no single region page and are not counted under each '
f'province: {links}. <a href="/?region={esc(CANADA_WIDE_KEY)}">Open in the trail finder</a>.</p></div>')
unit = "state" if country == "US" else "province or territory, or all of them"
blocks += f"""<div class="doc-block"><h2 id="{esc(country.lower())}">{esc(words.COUNTRIES[country])}</h2>
<p class="prose">{n_country} records name at least one {unit}. Each is counted once, whichever
country it is filed under.</p>
<div class="table-wrap"><table><thead><tr><th scope="col">State, province or territory</th><th scope="col">Records</th><th scope="col">With a downloadable track</th></tr></thead>
<tbody>{rows}</tbody></table></div>{extra}</div>"""
jump = []
for g, name, keys in facets.PLACE_GROUPS:
infos = sorted((by_slug[k.lower()] for k in keys if k.lower() in by_slug), key=lambda i: i["name"])
if not infos:
continue
recs = group_records(records, g)
jump.append(f'<li><a href="#{esc(g)}">{esc(name)} <span class="chips__n">{len(recs)}</span></a></li>')
rows = "".join(
f'<li><a href="{esc(facets.place_path(i["key"]))}">{esc(i["name"])}</a>'
f'<span class="places__n">{_plural(len(i["records"]))}</span></li>'
for i in infos)
blocks += f"""<section class="places__group" aria-labelledby="{esc(g)}">
<h2 id="{esc(g)}">{esc(name)}</h2>
<p class="places__sum">{_plural(len(recs))}, {_gpx_count(recs)} with a GPX here.
<a href="/?where=g:{esc(g)}">See them with the filters</a></p>
<ul class="places__list">{rows}</ul>
</section>"""
if across:
links = ", ".join(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>' for r in across)
jump.append(f'<li><a href="#across-canada">{facets.ACROSS_CANADA_NAME} <span class="chips__n">{len(across)}</span></a></li>')
blocks += f"""<section class="places__group" aria-labelledby="across-canada">
<h2 id="across-canada"><span id="canada-wide"></span>{facets.ACROSS_CANADA_NAME}</h2>
<p class="places__sum">{_plural(len(across))} that {"crosses" if len(across) == 1 else "cross"} the whole country rather than one province: {links}.
{"It is" if len(across) == 1 else "They are"} counted in every Canadian group, and on no single province&rsquo;s page.</p>
</section>"""
n_us = sum(1 for r in records if "US" in common.countries(r))
n_ca = sum(1 for r in records if "CA" in common.countries(r))
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">Browse</p><h1>Regions</h1>
<p class="page-head__lede">Every state, province and territory a record names. A record that
crosses several regions appears on each region's page, under the country that region belongs to.</p>
<div class="titleblock__text"><h1>Places</h1>
<p class="page-head__lede">The {len(records)} trails by state and province, grouped into parts of the
United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one&rsquo;s page.</p>
</div></header>
<dl class="tally">{tally}</dl></div></div>
<div class="container section">{blocks}</div>"""
return "Regions", "Long trails by state, province and territory, with counts of records and tracks.", Markup(body)
<ul class="chips" aria-label="Jump to a part of the country">{"".join(jump)}</ul></div></div>
<div class="container section places">{blocks}</div>"""
return "Places", "Long trails by state and province, grouped into parts of the United States and Canada.", Markup(body)
def region_page(slug, records, site):
"""(title, description, body, needs_map) for /regions/<slug>/: the trails in one state or province."""
by_slug, _ = collect_regions(records)
info = by_slug[slug]
recs = info["records"]
lines = sum(1 for r in recs if common.has_line(r))
key = words.region_key(info["code"], info["country"])
same = sorted((s for s, i in by_slug.items() if i["country"] == info["country"]),
key=lambda s: by_slug[s]["name"].lower())
idx = same.index(slug)
neighbours = []
if idx > 0:
p = by_slug[same[idx - 1]]
neighbours.append(f'<a href="{esc(region_path(p["code"], p["country"]))}">← {esc(p["name"])}</a>')
if idx + 1 < len(same):
n = by_slug[same[idx + 1]]
neighbours.append(f'<a href="{esc(region_path(n["code"], n["country"]))}">{esc(n["name"])} →</a>')
nav = " · ".join(neighbours)
with_line = (f'<a href="/?region={esc(key)}&amp;line=1">With a track</a>' if lines else "With a track")
key = info["key"]
group = info["group"]
group_name = facets.GROUP_NAME.get(group, "")
country = words.COUNTRIES[info["country"]]
n_gpx = _gpx_count(recs)
crumbs = '<li><a href="/regions/">Places</a></li>'
if group:
crumbs += f'<li><a href="/regions/#{esc(group)}">{esc(group_name)}</a></li>'
siblings = []
if group:
_, _, keys = next(x for x in facets.PLACE_GROUPS if x[0] == group)
for k in sorted(keys, key=facets.place_name):
if k != key and k.lower() in by_slug:
siblings.append(f'<a href="{esc(facets.place_path(k))}">{esc(facets.place_name(k))}</a>')
nav = (f'<nav class="region-nav" aria-label="Elsewhere in {esc(group_name)}">Elsewhere in {esc(group_name)}: '
f'{" · ".join(siblings)}</nav>') if siblings else ""
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/regions/">Regions</a></li>
<li><a href="/regions/#{esc(info["country"].lower())}">{esc(words.COUNTRIES[info["country"]])}</a></li>
<li aria-current="page">{esc(info["name"])}</li></ol></nav>
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{crumbs}<li aria-current="page">{esc(info["name"])}</li></ol></nav>
<header class="titleblock"><div class="titleblock__text">
<p class="kicker">{esc(words.COUNTRIES[info["country"]])} · {esc(info["code"])}</p>
<p class="kicker">{esc(group_name + " · " if group_name else "")}{esc(country)}</p>
<h1>{esc(info["name"])}</h1>
<p class="page-head__lede">{len(recs)} record{"s" if len(recs) != 1 else ""}, {lines} with a downloadable track.</p>
<p class="page-head__lede">{_plural(len(recs))} in {esc(info["name"])}, {n_gpx} with a GPX here.
<a href="/?where={esc(key)}">Narrow them with the filters</a>.</p>
</div></header>
<dl class="tally"><div><dt>Records</dt><dd>{len(recs)}</dd></div>
<div><dt>{common.SWATCH_LINE}{with_line}</dt><dd>{lines}</dd></div>
<div><dt>{common.SWATCH_NONE}Records only</dt><dd>{len(recs) - lines}</dd></div></dl>
</div></div>
<div class="container section">
<div class="section-head"><h2>Tracks in {esc(info["name"])}</h2><p>Only tracks in this region are drawn.</p></div>
{_region_map(recs, info["name"])}
</div>
<div class="container section">
<div class="section-head"><h2>Trails and routes in {esc(info["name"])}</h2>
<p><a href="/?region={esc(key)}">Open these in the trail finder</a> to search and filter them.</p></div>
<div class="container section place">
{home.overview_map(recs, f"Map of the trails in {info['name']}")}
{home.results(recs)}
<nav class="region-nav" aria-label="Neighbouring regions"><a href="/regions/">All regions</a>{f' · {nav}' if nav else ""}</nav>
{nav}
</div>"""
title = info["name"]
return title, f"{len(recs)} long trails and routes in {info['name']}, {words.COUNTRIES[info['country']]}.", Markup(body), bool(lines)
desc = f"{_plural(len(recs))} in {info['name']}, {country}: length, time and where to get the GPX."
return title, desc, Markup(body), n_gpx >= home.MAP_MIN
def route_guides(rec):
"""A route's guides, placed last in its list row on /routes/."""
"""A route's guides, compact, placed last in its row on /routes/."""
items = ""
for g in rec.get("guide", []):
access = g.get("access", "")
price = ""
if g.get("price"):
price = f' · {esc(g["price"])}'
if g.get("price_checked"):
price += f' (read {esc(g["price_checked"])})'
price = f' · {esc(g["price"])}' if g.get("price") else ""
fmt = f' · {esc(g["format"])}' if g.get("format") else ""
items += (f'<li><a href="{esc(g.get("url", ""))}">{esc(g.get("title", ""))}</a>'
f' <span class="access access--{esc(access)}">{esc(words.ACCESS.get(access, access))}</span>'
@@ -185,36 +142,84 @@ def route_guides(rec):
f'<ul class="route-guides">{items}</ul></div>')
def routes_page(records, site, repo_root):
"""(title, description, body) for /routes/."""
readme = docs.sections_map(docs.read_doc(repo_root, "README.md"))
inc = readme.get("Inclusion rule", "")
paras = [p for p in inc.split("\n\n") if "Person-defined rout" in p and "at the same 50-mile floor" in p]
bullets = [p for p in inc.split("\n\n") if "The creator sells" in p]
explainer = "\n\n".join(paras + bullets) or readme.get("Person-defined routes", "")
intro = docs.render_doc("## What a person-defined route is\n\n" + explainer, site)
policy_items = ""
for key in ("open", "sold", "withheld", "unclear"):
lab, short, rule = words.POLICIES[key]
policy_items += f'<li>{common.policy_chip(key)}<span>{esc(short)}. {esc(rule)}</span></li>'
policies = Markup(f'<ol class="policy-scale" aria-label="The four track policies">{policy_items}</ol>')
routes = [r for r in records if common.is_route(r)]
by_creator = collections.defaultdict(list)
def routes_page(records, site, repo_root=None):
"""(title, description, body, needs_map) for /routes/: the Routes list."""
routes = [r for r in records if facets.kind(r) == "route"]
by_author = collections.defaultdict(list)
for r in routes:
by_creator[r.get("route", {}).get("creator", "") or "Unknown"].append(r)
groups = [(esc(creator), sorted(by_creator[creator], key=home.sort_name), route_guides)
for creator in sorted(by_creator, key=str.lower)]
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><p class="kicker">Person-defined routes</p><h1>Routes</h1>
<p class="page-head__lede">{len(routes)} routes worked out and published by a person or a small group.</p>
by_author[facets.author(r) or "Author not named"].append(r)
groups = [(f"By {esc(a)}", sorted(by_author[a], key=home.sort_name), route_guides)
for a in sorted(by_author, key=str.lower)]
n_gpx = _gpx_count(routes)
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/">Trails</a></li>
<li><a href="/lists/">Lists</a></li><li aria-current="page">Routes</li></ol></nav>
<header class="titleblock"><div class="titleblock__text"><p class="kicker">A list</p><h1>Routes</h1>
<p class="page-head__lede" id="what-is-a-route">{esc(facets.ROUTE_DEFINITION)}</p>
</div></header></div></div>
<div class="container section"><div class="prose doc">{intro}</div>
<h2 class="doc-block">The four track policies</h2>{policies}
<p class="prose"><a href="/?kind=route">See the routes in the trail finder</a>, or read a route below.</p></div>
<div class="container section"><div class="section-head"><h2>Routes by creator</h2>
<p>Each route links to its record; its guides link out to the creator's or publisher's page.</p></div>
{home.results(groups=groups)}</div>"""
return "Routes", f"{len(routes)} person-defined routes by creator, with track policies and guides.", Markup(body)
<div class="container section">
<div class="prose">
<p>Every other trail on this site is an official trail. Being a route says who looks after it, not
how rough it is: some routes are on maintained trail all the way, and some official trails have
long road walks. The Walking line on each trail&rsquo;s page says what the walking is.</p>
<p>{_plural(len(routes), "route")}, by {len(by_author)} authors. {n_gpx} {"has" if n_gpx == 1 else "have"} a GPX here; for the rest,
each route&rsquo;s page says whether its author gives the track away, sells it, or does not publish it.
<a href="/?kind=route">Narrow them with the filters</a>.</p>
</div>
</div>
<div class="container section">
{home.overview_map(routes, "Map of the routes with a GPX here")}
{home.results(groups=groups, routes_list=True)}
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
</div>"""
return "Routes", f"{_plural(len(routes), 'route')} in the United States and Canada, by author, with their guides.", Markup(body), n_gpx >= home.MAP_MIN
def list_page(lst, recs, total, site):
"""(title, description, body, needs_map) for /lists/<key>/."""
n_gpx = _gpx_count(recs)
rule = (f"Lists are picked out by rule from each trail&rsquo;s facts, so they change as trails are added "
f"or corrected. A list is shown when it has at least {browse.MIN_SIZE} trails and no more than "
f"{round(browse.MAX_SHARE * 100)}% of the {total}.")
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/">Trails</a></li>
<li><a href="/lists/">Lists</a></li><li aria-current="page">{esc(lst.title)}</li></ol></nav>
<header class="titleblock"><div class="titleblock__text">
<p class="kicker">A list</p>
<h1>{esc(lst.title)}</h1>
<p class="page-head__lede">{esc(lst.blurb)} {_plural(len(recs))}, {n_gpx} with a GPX here.</p>
</div></header>
</div></div>
<div class="container section">
{home.overview_map(recs, f"Map of the trails in the list {lst.title}")}
{home.results(recs)}
<p class="finder__foot">{rule}</p>
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
</div>"""
return lst.title, f"{lst.title}: {lst.blurb}", Markup(body), n_gpx >= home.MAP_MIN
def lists_index_page(records, site):
"""(title, description, body) for /lists/: every list shown today, with a few of its trails."""
cards = []
for lst, recs in browse.shown(records):
sample = "".join(
f'<li><a href="{esc(common.trail_path(r))}">{common.name(r)}</a> '
f'<span class="shelf__len">{words.length(r["length_km"], "short", r["derived"]["length_mi"])}</span></li>'
for r in recs[:4])
cards.append(f"""<li class="shelf">
<h2 class="shelf__title"><a href="{esc(browse.path(lst))}">{esc(lst.title)}</a> <span class="shelf__count">{len(recs)}</span></h2>
<p class="shelf__blurb">{esc(lst.blurb)}</p>
<ul class="shelf__items">{sample}</ul>
<p class="shelf__more"><a href="{esc(browse.path(lst))}">See all {len(recs)}<span class="vh">: {esc(lst.title)}</span></a></p>
</li>""")
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/">Trails</a></li><li aria-current="page">Lists</li></ol></nav>
<header class="titleblock"><div class="titleblock__text"><h1>Lists</h1>
<p class="page-head__lede">Ready-made selections of the {len(records)} trails, a way to start. Each is
picked out by rule from what each trail&rsquo;s page says, so a list grows as trails are added.</p>
</div></header></div></div>
<div class="container section"><ul class="shelves">{"".join(cards)}</ul>
<p class="finder__foot">A list is shown when it has at least {browse.MIN_SIZE} trails and no more than
{round(browse.MAX_SHARE * 100)}% of all of them. To combine conditions, use the filters on <a href="/">the home page</a>.</p></div>"""
return "Lists", "Ready-made lists of long trails: National Scenic Trails, routes, loops, the longest and more.", Markup(body)
+459 -110
View File
@@ -8,7 +8,7 @@ import os
import re
import urllib.parse
from . import common, words
from . import common, elevation, facets, hike, words
from .markup import Markup, esc
EXTRACT_SOURCES = {"osm": "OpenStreetMap", "usfs": "USDA Forest Service", "nps": "National Park Service"}
@@ -70,18 +70,15 @@ def restates_no_line(value):
def region_names(rec):
"""The regions for the title block, each linked to its region page."""
regions = rec.get("regions", [])
if len(regions) <= 3:
parts = []
for code_ in regions:
if code_ == words.ALL_CANADA:
href = "/regions/#canada-wide"
else:
href = f"/regions/{words.region_key(code_, rec['country']).lower()}/"
parts.append(f'<a href="{esc(href)}">{esc(words.region_name(code_))}</a>')
return Markup(", ".join(parts))
return common.regions_html(rec, linked=True)
"""The states and provinces for the glance, each linked to its place page; codes when there are many."""
keys = facets.place_keys(rec)
parts = []
for key in keys:
name = facets.place_name(key)
text = esc(name) if len(keys) <= 3 or key == facets.ACROSS_CANADA else \
Markup(f'<abbr title="{esc(name)}">{esc(key.split("-", 1)[1])}</abbr>')
parts.append(f'<a href="{esc(facets.place_path(key))}">{text}</a>')
return Markup((", " if len(keys) <= 3 else " ").join(parts))
_ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)")
@@ -96,66 +93,198 @@ def org_name(text):
# Page head ------------------------------------------------------------------
def kind_word(rec):
return "route" if common.is_route(rec) else "trail"
def place_text(rec):
"""Where it is, for a sentence: "in Oregon, United States", "across 14 states of the
United States", "across 9 states and provinces of the United States and Canada"."""
codes = rec.get("regions", [])
countries = [words.COUNTRIES.get(c, c) for c in common.countries(rec)] or \
[words.COUNTRIES.get(rec["country"], rec["country"])]
country = words.join_names(countries)
if words.ALL_CANADA in codes or not codes:
return f"across {country}" if words.ALL_CANADA in codes else f"in {country}"
if len(codes) > 3:
unit = {"United States": "states", "Canada": "provinces and territories"}.get(country, "states and provinces")
the = words.join_names(("the " + c) if c == "United States" else c for c in countries)
return f"across {len(codes)} {unit} of {the}"
return f"in {words.join_names(words.region_name(c) for c in codes)}, {country}"
def fallback_lede(rec):
"""A one-sentence description built from the record, for a record without a [hike] summary."""
length_html = words.length(rec["length_km"], "inline", rec["derived"]["length_mi"])
return Markup(f"A {kind_word(rec)} of {length_html} {esc(place_text(rec))}.")
def lead_line(rec):
"""Who made or designated it: "Route by Steve Roper, 1970", or the trail's designation."""
if common.is_route(rec):
return facets.route_by(rec)
return rec.get("designation", "")
def route_definition():
"""What a route is, one tap away from the Kind line of a route's page (no script needed)."""
return Markup(f'<details class="define"><summary>What is a route?</summary>'
f'<p>{esc(facets.ROUTE_DEFINITION)} <a href="/routes/">Every route</a>.</p></details>')
def official_link(rec):
"""(url, label) of the trail's own page: the [hike] official site, else the
publisher's page for the trail, else a route's free guide; None when the record has none."""
url = hike.official_url(rec)
if url:
return url, "Official site"
src = rec.get("source", {})
if src.get("publisher_url"):
who = org_name(src.get("publisher", ""))
return src["publisher_url"], (f"{who} website" if who else "The trail's website")
if common.is_route(rec):
for g in rec.get("guide", []):
if g.get("url"):
return g["url"], "The route's guide"
return None
def page_head(rec):
route = common.is_route(rec)
country = words.COUNTRIES.get(rec["country"], rec["country"])
crumbs = [f'<li><a href="/">Trails</a></li>',
f'<li><a href="/?country={esc(rec["country"])}">{esc(country)}</a></li>']
if route:
crumbs.append('<li><a href="/?kind=route">Person-defined routes</a></li>')
crumbs = ['<li><a href="/regions/">Places</a></li>']
keys = facets.place_keys(rec)
groups = facets.place_groups(rec)
if keys and keys[0] in facets.GROUP_OF:
g = facets.GROUP_OF[keys[0]]
crumbs.append(f'<li><a href="/regions/#{esc(g)}">{esc(facets.GROUP_NAME[g])}</a></li>')
crumbs.append(f'<li><a href="{esc(facets.place_path(keys[0]))}">{esc(facets.place_name(keys[0]))}</a></li>')
elif groups:
crumbs.append(f'<li><a href="/regions/#across-canada">{esc(facets.ACROSS_CANADA_NAME)}</a></li>')
crumbs.append(f'<li aria-current="page">{common.name(rec)}</li>')
if route:
r = rec["route"]
lead = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "")
else:
lead = rec.get("designation", "")
sub = f'{esc(lead)} &middot; {region_names(rec)}, {esc(country)}'
has_plate = bool(common.shield_url(rec))
plate = common.plate(rec, size="lg", link=True, eager=True) if has_plate else ""
summary = hike.summary(rec)
lede = common.rich(summary) if summary else fallback_lede(rec)
actions = []
official = official_link(rec)
if official:
actions.append(f'<a class="button button--link" href="{esc(official[0])}">{esc(official[1])} {common.ICON_EXTERNAL}</a>')
if rec["derived"].get("downloads"):
actions.append(f'<a class="button button--primary" href="#download">{common.ICON_DOWNLOAD}Download the GPX</a>')
else:
actions.append(f'<a class="button button--quiet" href="#track">GPX: {esc(facets.GPX_STATUS[facets.gpx(rec)])}</a>')
tag_html = common.badges(rec)
kicker = f'<p class="cluster">{tag_html}</p>' if tag_html else ""
lead = lead_line(rec)
define = route_definition() if route else ""
return f"""<div class="page-head">
<div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{"".join(crumbs)}</ol></nav>
<header class="titleblock{" titleblock--with-plate" if has_plate else ""}">
{plate}
<div class="titleblock__text">
<p class="cluster">{common.tags(rec)}</p>
{kicker}
<h1>{common.name(rec)} <span class="titleblock__abbr">{esc(rec.get("short_name", ""))}</span></h1>
<p class="titleblock__sub">{sub}</p>
{f'<p class="titleblock__sub">{common.rich(lead)}</p>' if lead else ""}
{define}
</div>
</header>
{tally(rec)}
<p class="trail-lede">{lede}</p>
<p class="cluster trail-actions">{"".join(actions)}</p>
</div>
</div>"""
def tally(rec):
v = rec.get("verification", {})
note = rec.get("length_note", "")
if note.replace(",", "") in (f"{rec['length_km']} km", f"{rec['length_km']} km published"):
note = "" # the note only repeats the number
items = [("Published length", words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]), note)]
if v.get("verified") and "measured_km" in v:
diff = v.get("difference_percent", 0)
items.append(("Measured track", words.length(v["measured_km"], "stack", measured=True),
f"{words.fmt_percent(diff)} against published"))
def glance_row(label, value, note="", wide=False):
note_html = f"<small>{note if isinstance(note, Markup) else esc(note)}</small>" if note else ""
value_html = value if isinstance(value, Markup) else esc(value)
return Markup(f'<div{" class=\"glance__wide\"" if wide else ""}><dt>{esc(label)}</dt>'
f'<dd>{value_html}{note_html}</dd></div>')
def glance(rec):
"""The hiker's facts at a glance, under the attribute names every page uses."""
h = hike.table(rec)
rows = [glance_row(facets.LENGTH, words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]))]
rows.append(glance_row(facets.TIME, facets.time_text(rec), facets.estimate_note(rec)))
season = facets.season_text(rec)
if season:
rows.append(glance_row(facets.SEASON, season))
if facets.walking(rec):
rows.append(glance_row(facets.WALKING, facets.WALKING_VALUES[facets.walking(rec)]))
elev = elevation.get(rec)
if h.get("high_point") or h.get("high_point_m"):
# A named, sourced high point is better than a computed number.
value = Markup(esc(h.get("high_point", "")))
if h.get("high_point_m"):
value = Markup(f'{value}{"<br>" if h.get("high_point") else ""}{words.elevation(h["high_point_m"])}')
rows.append(glance_row("High point", value))
elif elev:
rows.append(glance_row("High point", words.elevation(elev["highest"]["m"]),
elevation.COMPUTED_NOTE))
if elev:
low = elev["lowest"]
low_note = ("Sea level. " if elevation.is_sea_level(low) else "") + elevation.COMPUTED_NOTE
rows.append(glance_row("Low point", words.elevation(low["m"]), low_note))
climb = Markup(str(words.elevation(elev["ascent_m"])))
if elevation.show_descent(elev):
climb = Markup(f'{climb}<br>Descent: {words.elevation(elev["descent_m"])}')
if facets.shape(rec) == "loop":
climb_note = elevation.COMPUTED_NOTE
else:
climb_note = f"Computed from the track, {elevation.direction_words(elev)}."
rows.append(glance_row("Climb", climb, climb_note))
ends = hike.ends(rec)
if ends:
label, text = ends
if isinstance(text, tuple):
text = Markup(f'{esc(text[0])}<span class="glance__to"> to </span>{esc(text[1])}')
if facets.shape(rec):
text = Markup(f'<strong>{esc(facets.SHAPES[facets.shape(rec)])}.</strong> {esc(text) if not isinstance(text, Markup) else text}')
label = facets.SHAPE
rows.append(glance_row(label, text, wide=True))
elif facets.shape(rec):
rows.append(glance_row(facets.SHAPE, facets.SHAPES[facets.shape(rec)]))
terrain = facets.terrain(rec)
if terrain:
rows.append(glance_row(facets.TERRAIN, ", ".join(words.TERRAIN[t] for t in terrain), wide=True))
if h.get("permit"):
rows.append(glance_row("Permits", common.sentence(h["permit"]), wide=True))
country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec))
rows.append(glance_row(facets.WHERE, Markup(f'{region_names(rec)}, {esc(country)}'), wide=True))
status = facets.gpx(rec)
if facets.gpx_here(rec):
text = facets.GPX_STATUS[status]
value = Markup(f'<a href="#download">{esc(text)}</a>') if rec["derived"].get("downloads") else text
note = common.partial_short_text(rec) if common.line_differs(rec) else ""
else:
items.append(("Measured track", Markup('<span class="tally__none">Not measured</span>'),
"No track was downloaded and measured"))
if common.has_line(rec):
text = "In the dataset, partial" if common.line_short(rec) else "In the dataset"
link = Markup(f'<a href="#download">{esc(text)}</a>') if rec["derived"].get("downloads") else text
items.append(("Track", link, "Licence: " + common.licence_label(rec)))
else:
items.append(("Track", "Record only", "The reason is given below"))
if common.is_route(rec):
p = common.policy(rec)
items.append(("Track policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p)))
else:
t = rec.get("tier", "")
items.append(("Tier", words.label(words.TIERS, t), words.meaning(words.TIERS, t)))
cells = "".join(f'<div><dt>{esc(a)}</dt><dd>{esc(b)}{f"<small>{esc(c)}</small>" if c else ""}</dd></div>'
for a, b, c in items)
return Markup(f'<dl class="tally tally--trail">{cells}</dl>')
value = Markup(f'<a href="#track">{esc(facets.GPX_STATUS[status])}</a>')
note = ""
rows.append(glance_row(facets.GPX, value, note, wide=True))
halves = [i for i, r in enumerate(rows) if 'class="glance__wide"' not in r]
if len(halves) % 2: # an odd one out takes the full width rather than leave a gap beside it
i = halves[-1]
rows[i] = Markup(rows[i].replace("<div>", '<div class="glance__wide">', 1))
caution = ""
if h.get("caution"):
caution = f'<p class="glance__warn"><strong>Know before you go.</strong> {common.rich(common.sentence(h["caution"]))}</p>'
unfinished = ""
if h.get("unfinished"):
unfinished = f'<p class="glance__warn"><strong>Not finished.</strong> {common.rich(common.sentence(h["unfinished"]))}</p>'
missing = [name for name, have in ((facets.SEASON, season), (facets.TERRAIN, terrain),
(facets.WALKING, facets.walking(rec))) if not have]
pending = ""
if missing:
names = words.join_names([missing[0]] + [m.lower() for m in missing[1:]])
verb = "is" if len(missing) == 1 else "are"
pending = f'<p class="note">{esc(names)} {verb} not on file for this trail yet.</p>'
elev_caveat = elevation.coverage_caveat(elev) if elev else ""
elev_note = f'<p class="note">{esc(elev_caveat)}</p>' if elev_caveat else ""
return f"""<section class="glance detail__glance" aria-labelledby="glance-title">
<h2 class="glance__title" id="glance-title">At a glance</h2>
<dl class="glance__facts">{"".join(rows)}</dl>
{unfinished}{caution}{elev_note}{pending}
</section>"""
# Map or empty frame ---------------------------------------------------------
@@ -187,25 +316,65 @@ def map_figure(rec):
</figure>"""
def elevation_figure(rec):
"""The elevation profile under the map, drawn as SVG at build time. With too
many parts (olt/elevation.py) there is no line to draw in walking order, so
the section says that and states the figures instead."""
elev = elevation.get(rec)
if not elev:
return ""
loop = facets.shape(rec) == "loop"
sentence = elevation.summary_sentence(elev, loop)
caveat = elevation.coverage_caveat(elev)
caveat_html = f'<p class="note">{esc(caveat)}</p>' if caveat else ""
if not elevation.show_profile(elev):
return f"""<section class="elev detail__profile" aria-labelledby="elevation-title">
<h2 class="elev__title" id="elevation-title">Elevation profile</h2>
<div class="elev__body">
<p>{esc(elevation.parts_caveat(elev))}</p>
<p>{esc(sentence)}</p>
{caveat_html}
</div>
</section>"""
parts = elev.get("parts") or 1
breaks = (f" The line breaks where the track does: it has {parts} parts, and no climb "
"is counted across a gap.") if parts > 1 else ""
return f"""<section class="elev detail__profile" aria-labelledby="elevation-title">
<h2 class="elev__title" id="elevation-title">Elevation profile</h2>
<figure class="elev__figure">
{elevation.profile_svg(elev, loop)}
<figcaption><p>{esc(sentence)}{esc(breaks)}</p>{caveat_html}</figcaption>
</figure>
</section>"""
def free_guides(rec):
return [g for g in rec.get("guide", []) if g.get("access") == "free"]
ROUTE_NO_GPX = {
# GPX status -> (heading, what this site does about it)
"free": ("Get the GPX from its author",
"A GPX is included here only where the author's terms allow passing it on, or where "
"OpenStreetMap maps the route. Otherwise the author's own page is the place to get it."),
"sold": ("The author sells the route as a guide",
"No GPX is included here from any source, OpenStreetMap included, so the author's work is respected."),
"unpublished": ("The author does not publish a track",
"No GPX is included here from any source, OpenStreetMap included, so the author's choice is respected."),
"elsewhere": ("No GPX here",
"No GPX is included here until it is clear that the author allows it."),
}
def empty_frame(rec):
"""The map frame of a trail with no GPX here: why, and where to get one."""
src = rec["source"]
reason = src.get("line_absent_reason", "")
actions = []
status = facets.gpx(rec)
if common.is_route(rec):
p = common.policy(rec)
titles = {
"open": "Get the track from the creator",
"sold": "The track is sold as a guide",
"withheld": "The creator does not publish a track",
"unclear": "Whether the track may be shared is not settled",
}
title = titles.get(p, "No track in this dataset")
rule = words.POLICIES.get(p, ("", "", ""))[2]
if p == "open" and free_guides(rec):
title, rule = ROUTE_NO_GPX.get(status, ROUTE_NO_GPX["elsewhere"])
if status == "free" and free_guides(rec):
g = free_guides(rec)[0]
actions.append(f'<a class="button button--primary" href="{esc(g["url"])}">'
f'{esc(g["title"])} {common.ICON_EXTERNAL}</a>')
@@ -214,31 +383,42 @@ def empty_frame(rec):
elif len(rec.get("guide", [])) > 1:
actions.append('<a class="button button--link" href="#guides-title">All guides</a>')
else:
title = "No track in this dataset"
title = "No GPX here"
reason = common.absent_reason_short(rec)
rule = "A trail may be listed as a record only, with no track, when no track for it may be shared. The record says why."
if src.get("publisher_url"):
actions.append(f'<a class="button button--link" href="{esc(src["publisher_url"])}">'
f'Publisher&rsquo;s page {common.ICON_EXTERNAL}</a>')
elif src.get("url"):
rule = "A trail is listed without a GPX when no track for it may be passed on."
official = official_link(rec)
if official:
actions.append(f'<a class="button button--link" href="{esc(official[0])}">'
f'{esc(official[1])} {common.ICON_EXTERNAL}</a>')
places = [official[1][:1].lower() + official[1][1:] if official[1] == "Official site"
else "the " + official[1]] if official else []
if src.get("url") and (not official or src["url"] != official[0]):
osm = host(src["url"]).endswith("openstreetmap.org")
label = "See it on OpenStreetMap" if osm else "Where to ask for the track"
places.append("OpenStreetMap, where the trail is mapped" if osm else "the track's source")
actions.append(f'<a class="button button--link" href="{esc(src["url"])}">'
f'The source {common.ICON_EXTERNAL}</a>')
f'{esc(label)} {common.ICON_EXTERNAL}</a>')
if places:
places[0] = places[0].replace("official site", "the official site")
lead = f"For a track, try {words.join_names(places)}."
reason = Markup(f'{esc(lead)}</p><p class="note"><strong>Why there is none here:</strong> '
f'{common.rich(reason)}')
actions_html = f'<p class="cluster">{"".join(actions)}</p>' if actions else ""
return f"""<figure class="mapfig mapfig--empty detail__map" aria-labelledby="noline-title">
return f"""<figure class="mapfig mapfig--empty detail__map" id="track" aria-labelledby="noline-title">
<div class="mapfig__frame">
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true">No track in this dataset</span>
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true">No GPX here</span>
<div class="map map--empty">
<div class="map__message">
<p class="kicker">Record only</p>
<p class="kicker">GPX: {esc(facets.GPX_STATUS[status])}</p>
<h2 id="noline-title">{esc(title)}</h2>
<p>{common.rich(reason)}</p>
<p class="map__reason">{reason if isinstance(reason, Markup) else common.rich(reason)}</p>
<p class="note">{esc(rule)}</p>
{actions_html}
</div>
</div>
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true">Nothing drawn</span>
</div>
<figcaption class="mapfig__caption"><p>No map is drawn: the dataset holds no track for this {"route" if common.is_route(rec) else "trail"}, and does not guess one.</p></figcaption>
<figcaption class="mapfig__caption"><p>No map is drawn: there is no track for this trail here, and the site does not guess one.</p></figcaption>
</figure>"""
@@ -368,7 +548,7 @@ def guides_panel(rec):
<h2 class="panel__head" id="guides-title">Where to get the route</h2>
<div class="panel__body">
<ul class="guides">{cards}</ul>
<p class="note">Links go to the creator&rsquo;s or publisher&rsquo;s own page for each guide.</p>
<p class="note">Links go to the author&rsquo;s or publisher&rsquo;s own page for each guide.</p>
</div>
</section>"""
@@ -377,7 +557,7 @@ def _is_url(value):
return isinstance(value, str) and value.startswith(("http://", "https://"))
def links_panel(rec):
def links_block(rec):
"""Every link the record holds, each titled with the organisation or person the
record names for it, with the host name and what the link is as secondary text."""
src = rec["source"]
@@ -424,10 +604,7 @@ def links_panel(rec):
return f"{host(url)} · {text}" if _is_url(url) else text
lis = "".join(f'<li>{ext_link(u, t)}<small>{esc(describe(u, w))}</small></li>' for u, (t, w) in items.items())
return f"""<section class="panel" aria-labelledby="links-title">
<h2 class="panel__head" id="links-title">Links</h2>
<div class="panel__body"><ul class="linklist">{lis}</ul></div>
</section>"""
return block("links-title", "Links", Markup(f'<ul class="linklist">{lis}</ul>'))
# Main column ----------------------------------------------------------------
@@ -439,14 +616,14 @@ def policy_scale(current):
here = ' aria-current="true"' if p == current else ""
mark = '<span class="policy-scale__here">This route</span>' if p == current else ""
items.append(f'<li{here}>{common.policy_chip(p)}<span>{esc(short)}. {esc(rule)}</span>{mark}</li>')
return Markup(f'<ol class="policy-scale" aria-label="Track policies for person-defined routes">{"".join(items)}</ol>')
return Markup(f'<ol class="policy-scale" aria-label="Track policies for routes">{"".join(items)}</ol>')
def route_block(rec):
r = rec["route"]
p = r.get("line_policy", "")
rows = [
fact("Creator", r.get("creator", "")),
fact("Author", r.get("creator", ""), "Who worked the route out (route.creator)"),
fact("First published", str(r["year"])) if r.get("year") else
fact("First published", "Not recorded", "No page read states a year"),
fact("Track policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p)),
@@ -454,8 +631,8 @@ def route_block(rec):
quote = ""
if r.get("creator_words"):
by = r.get("creator_words_by") or r.get("creator", "")
not_creator = ('<span class="tag tag--quiet">Not the creator&rsquo;s words</span>'
if r.get("creator_words_by") else '<span class="tag tag--quiet">The creator&rsquo;s words</span>')
not_creator = ('<span class="tag tag--quiet">Not the author&rsquo;s words</span>'
if r.get("creator_words_by") else '<span class="tag tag--quiet">The author&rsquo;s words</span>')
url = r.get("creator_words_url", "")
quote = f"""<figure class="quote">
<blockquote{f' cite="{esc(url)}"' if url else ""}><p>{esc(r["creator_words"])}</p></blockquote>
@@ -488,7 +665,9 @@ def record_block(rec):
country = words.COUNTRIES.get(rec["country"], rec["country"])
names = ", ".join(words.region_name(c) for c in rec.get("regions", []) if c != words.ALL_CANADA)
names_html = f' <span class="muted">({esc(names)})</span>' if names else ""
where = Markup(f'{common.regions_html(rec, linked=True)}{names_html}, {esc(country)}')
codes = Markup(" ".join(f'<a href="{esc(facets.place_path(k))}">{esc(k.split("-", 1)[1] if k != facets.ACROSS_CANADA else facets.ACROSS_CANADA_NAME)}</a>'
for k in facets.place_keys(rec)))
where = Markup(f'{codes}{names_html}, {esc(country)}')
rows = [
fact("Kind", words.label(words.KINDS, k), words.meaning(words.KINDS, k)),
fact("Designation", rec.get("designation", "")),
@@ -564,6 +743,85 @@ def verification_block(rec):
return block("verify-title", "Verification", rows + record_text(v.get("note", "")) + Markup(gap_html))
def _coord(point):
lat, lon = point.get("lat"), point.get("lon")
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
return f"At {lat:.5f}, {lon:.5f} (latitude, longitude)"
return ""
def _fmt_number(value):
if isinstance(value, float) and value.is_integer():
return f"{int(value):,}"
return f"{value:,}" if isinstance(value, (int, float)) else str(value)
def elevation_block(rec):
"""How the elevation figures were computed, the model's credit, and every value."""
elev = elevation.get(rec)
if not elev:
return ""
src = elev.get("source") or {}
model = src.get("model", "")
loop = facets.shape(rec) == "loop"
direction = elevation.direction_words(elev)
climb_note = elevation.COMPUTED_NOTE if loop else \
f"Computed from the track, {direction}. Walking the other way swaps climb and descent."
low_note = _coord(elev["lowest"])
if elevation.is_sea_level(elev["lowest"]):
low_note = ("Sea level. " + low_note).strip()
coverage = elev.get("coverage")
coverage_text = (f"{coverage:.3f} ({elevation.coverage_percent(elev)} of the published length)"
if isinstance(coverage, (int, float)) else str(coverage))
starts = elev.get("part_starts_km") or []
rows = [
fact("Highest point on the track", words.elevation(elev["highest"]["m"]), _coord(elev["highest"])),
fact("Lowest point on the track", words.elevation(elev["lowest"]["m"]), low_note),
fact("Total climb", words.elevation(elev["ascent_m"]), climb_note),
fact("Total descent", words.elevation(elev["descent_m"]), climb_note),
fact("Length sampled", words.length(elev["track_km"], "inline", measured=True),
"The length of the track, not the published length"),
fact("Published length", words.length(elev["published_km"], "inline")),
fact("Coverage", coverage_text, elevation.coverage_caveat(elev) or
"Length sampled divided by the published length"),
fact("Parts", str(elev.get("parts", "")),
"Pieces left after joining track ends within 100 m, counted for the elevation sampling. "
"It can differ from the count under Verification, which was made with another joining rule. "
"No climb is counted across a gap."),
]
if starts:
rows.append(fact("Part starts", ", ".join(words.fmt_km1(s) for s in starts) + " km",
"The distance along the profile where each part after the first begins"))
if not elevation.show_profile(elev):
rows.append(fact("Profile", "Not drawn", elevation.parts_caveat(elev)))
rows += [
fact("Elevation model", model) if model else "",
Markup(f'<div><dt>Model page</dt><dd>{ext_link(src["url"])}</dd></div>') if src.get("url") else "",
fact("Model credit", src.get("attribution", ""), "The credit to show, as the model gives it")
if src.get("attribution") else "",
fact("Tiles", f"Zoom {_fmt_number(src['zoom'])}, about {_fmt_number(src['ground_m_per_pixel_at_40n'])} m "
"per cell at 40 degrees north")
if src.get("zoom") is not None and src.get("ground_m_per_pixel_at_40n") is not None else "",
fact("Sampling", f"Every {_fmt_number(src['sample_spacing_m'])} m along the track")
if src.get("sample_spacing_m") is not None else "",
fact("Smoothing", src.get("smoothing", "")) if src.get("smoothing") else "",
fact("Computed", str(src["computed"])) if src.get("computed") else "",
fact("Method version", str(src["method_version"])) if src.get("method_version") is not None else "",
]
spacing = src.get("sample_spacing_m")
sampled = (f"A point was taken every {_fmt_number(spacing)} m along each part of the track, "
"and its elevation was read from the model. ") if spacing is not None else ""
smoothing = src.get("smoothing", "")
method = (f"These figures were computed from the trail&rsquo;s track and {esc(model)}, "
f"not read from a page about the trail. {esc(sampled)}"
+ (f"Smoothing and counting: {esc(smoothing.rstrip('.').lower()[:1] + smoothing.rstrip('.')[1:])}."
if smoothing else ""))
limits = src.get("limits", "")
limits_html = (f'<h3 class="block__sub">Limits</h3>{record_text(limits)}') if limits else ""
content = Markup(f'<p class="record-text">{method}</p>') + facts(*rows) + Markup(limits_html)
return block("elevation-data-title", "Elevation", content)
def source_block(rec):
src = rec["source"]
line = common.has_line(rec)
@@ -660,7 +918,7 @@ def correction_block(rec, site):
if common.is_route(rec):
parts.append(f"""<div class="notice">
<h3>If you made this route</h3>
<p>A route&rsquo;s creator can ask for its record to be corrected or removed, and the record will be corrected or removed. Say which route: {code(rec["id"])}. See <a href="/about/">About</a>.</p>
<p>The author of a route can ask for its record to be corrected or removed, and the record will be corrected or removed. Say which route: {code(rec["id"])}. See <a href="/about/">About</a>.</p>
</div>""")
if site.is_github:
report = esc(site.correction_url(rec["id"], rec.get("name", "")))
@@ -679,6 +937,50 @@ def correction_block(rec, site):
return block("correct-title", "Corrections", Markup("".join(parts)))
def hike_sources_block(rec):
"""Where the hiker facts at the top of the page were read."""
h = hike.table(rec)
if not h:
return ""
items = ""
for src in hike.sources(rec):
url = src.get("url", "")
who = src.get("publisher") or (host(url) if url else "Source")
facts_ = [words.HIKE_FACTS.get(f, f) for f in src.get("facts", [])]
what = ("For " + words.join_names(facts_)) if facts_ else ""
link = ext_link(url, who) if url else esc(who)
detail = " · ".join(x for x in (host(url) if url else "", what) if x)
items += f"<li>{link}{f'<small>{esc(detail)}</small>' if detail else ''}</li>"
body = f'<ul class="linklist">{items}</ul>' if items else \
'<p class="record-text">The record names no page for these facts.</p>'
checked = f'<p class="note">Checked {esc(h["checked"])}.</p>' if h.get("checked") else ""
return block("hike-title", "Where the hiking facts come from", Markup(body + checked))
def about_data(rec, site):
"""Everything about where the page's data comes from: collapsed, below the hiker's part."""
blocks = ((route_block(rec) if common.is_route(rec) else "") + record_block(rec) + hike_sources_block(rec)
+ verification_block(rec) + elevation_block(rec) + source_block(rec) + osm_block(rec) + logo_block(rec)
+ links_block(rec) + correction_block(rec, site) + raw_record(rec))
return f"""<details class="about-data" id="about-data">
<summary><h2 id="about-data-title">About this data</h2>
<span class="about-data__hint">Where the track and the facts come from, licence, checks, the logo, corrections, and every field of the record</span></summary>
<div class="about-data__body detail__main">
{blocks}
</div>
</details>"""
def page_foot(rec, site):
"""The plain lines under the hiker's part: not for navigation, and how to report a problem."""
report = ""
if site.repo_url:
report = (f' Something wrong on this page? '
f'<a href="{esc(site.correction_url(rec["id"], rec.get("name", "")))}">Report a problem</a>.')
return (f'<p class="page-foot">Not for navigation: check the trail&rsquo;s own maps '
f'and current conditions before you go.{report}</p>')
def flatten(obj, prefix=""):
"""(field, value) for every leaf of a record: "source.licence", "guide[0].title", "regions[1]"."""
if isinstance(obj, dict):
@@ -719,35 +1021,82 @@ def raw_record(rec):
# The page -------------------------------------------------------------------
def description(rec):
km = words.fmt_km(rec["length_km"])
mi = words.fmt_int(rec["derived"]["length_mi"])
where = ", ".join(words.region_name(c) for c in rec.get("regions", [])[:3])
if len(rec.get("regions", [])) > 3:
where += " and more"
kind = "person-defined route" if common.is_route(rec) else "long trail"
text = f"{rec['name']}: a {km} km ({mi} mi) {kind} in {where}. "
if common.has_line(rec):
text += "Download its track as GPX or GeoJSON, with the source, licence and credit."
one = hike.one_line(rec)
if one:
text = one
else:
text += "Record only: " + common.absent_reason_short(rec)
km = words.fmt_km(rec["length_km"])
mi = words.fmt_int(rec["derived"]["length_mi"])
text = f"{rec['name']}: a {kind_word(rec)} of {km} km ({mi} mi) {place_text(rec)}."
text += (" Download its GPX here." if common.has_line(rec)
else " Where to get its GPX.")
return text if len(text) <= 300 else text[:297].rsplit(" ", 1)[0] + "…"
def render(rec, site):
"""Return (title, description, body HTML, needs_map) for one record."""
# Ways onward ------------------------------------------------------------------
ONWARD_MAX = 6
def _onward_list(title, recs, more_href, more_text, heading_id):
items = "".join(
f'<li><a href="{esc(common.trail_path(r))}">{common.name(r)}</a>'
f'<span class="onward__len">{words.length(r["length_km"], "short", r["derived"]["length_mi"])}'
f'{" · Route" if common.is_route(r) else ""}</span></li>'
for r in recs[:ONWARD_MAX])
more = (f'<p class="onward__more"><a href="{esc(more_href)}">{esc(more_text)}</a></p>'
if more_href else "")
return (f'<section class="onward__part" aria-labelledby="{heading_id}">'
f'<h3 id="{heading_id}">{esc(title)}</h3><ul class="onward__list">{items}</ul>{more}</section>')
def onward(rec, records):
"""Ways onward at the foot of the page: other trails in the same state or province
(up to three of them), and for a route, other routes by the same author."""
if not records:
return ""
others = [r for r in records if r["id"] != rec["id"]]
parts = []
for i, key in enumerate(k for k in facets.place_keys(rec) if k != facets.ACROSS_CANADA):
if i >= 3:
break
here = sorted((r for r in others if key in facets.place_keys(r)), key=lambda r: -r["length_km"])
if not here:
continue
name = facets.place_name(key)
more = (facets.place_path(key), f"All {len(here) + 1} trails in {name}") if len(here) > ONWARD_MAX else \
(facets.place_path(key), f"{name} on the map")
parts.append(_onward_list(f"More in {name}", here, more[0], more[1], f"onward-{key.lower()}"))
who = facets.author(rec)
if who:
same = sorted((r for r in others if facets.author(r) == who), key=lambda r: -r["length_km"])
if same:
parts.append(_onward_list(f"More routes by {who}", same, "/routes/", "Every route", "onward-author"))
if not parts:
return ""
return (f'<nav class="onward" aria-labelledby="onward-title"><h2 id="onward-title">Where next</h2>'
f'<div class="onward__grid">{"".join(parts)}</div></nav>')
def render(rec, site, records=None):
"""Return (title, description, body HTML, needs_map) for one trail.
records: every trail, for the ways onward at the foot (left out when None)."""
has_map = common.has_line(rec)
aside = downloads_panel(rec) + guides_panel(rec) + links_panel(rec)
main = (route_block(rec) if common.is_route(rec) else "") + record_block(rec) + verification_block(rec) \
+ source_block(rec) + osm_block(rec) + logo_block(rec) + correction_block(rec, site) + raw_record(rec)
aside = downloads_panel(rec) + guides_panel(rec)
aside_html = (f'<aside class="detail__aside" aria-label="{"Downloads" if has_map else "Where to get the route"}">'
f'{aside}</aside>') if aside else ""
profile = elevation_figure(rec)
body = f"""{page_head(rec)}
<div class="container detail">
<div class="container detail{"" if aside else " detail--no-aside"}{"" if has_map else " detail--no-map"}{" detail--with-profile" if profile else ""}">
{glance(rec)}
{map_figure(rec) if has_map else empty_frame(rec)}
<aside class="detail__aside" aria-label="{"Downloads and links" if has_map else "Where to get it, and links"}">
{aside}
</aside>
<div class="detail__main">
{main}
</div>
{profile}
{aside_html}
</div>
<div class="container trail-more">
{onward(rec, records)}
{page_foot(rec, site)}
{about_data(rec, site)}
</div>"""
return rec["name"], description(rec), body, has_map
+72 -9
View File
@@ -47,10 +47,11 @@ INCLUSION = {
"candidate-decision-pending": ("Candidate", "The decision to list it is pending"),
}
KINDS = {
"designated": ("Designated trail",
"Designated, maintained and published as one trail by a land agency or a trail association"),
"route": ("Person-defined route",
"Worked out and published by a person or a small group: a high route, a traverse or a loop of linked trails"),
"designated": ("Official trail",
"Looked after as one trail by a land agency or a trail association"),
"route": ("Route",
"A trail that a hiker worked out and published. No agency or association looks after it "
"as one trail, and there may be no signs for it"),
}
SOURCE_STATUS = {
"verified": ("Verified", "The track was downloaded from the source and measured"),
@@ -75,14 +76,14 @@ LICENCE_URLS = {
"CC-BY-NC-ND-4.0": "https://creativecommons.org/licenses/by-nc-nd/4.0/",
}
POLICIES = {
"open": ("Open", "The creator publishes the track freely",
"A track is included only where the creator's terms allow passing it on, or where "
"OpenStreetMap carries the route as a route relation. Otherwise get it from the creator."),
"open": ("Open", "The author publishes the track freely",
"A track is included only where the author's terms allow passing it on, or where "
"OpenStreetMap carries the route as a route relation. Otherwise get it from the author."),
"sold": ("Sold", "The route is got by buying a guide or map set",
"No track is included from any source, OpenStreetMap included."),
"withheld": ("Withheld", "The creator chooses not to publish a track",
"withheld": ("Withheld", "The author chooses not to publish a track",
"No track is included from any source, OpenStreetMap included."),
"unclear": ("Unclear", "Whether the creator shares the track is not settled",
"unclear": ("Unclear", "Whether the author shares the track is not settled",
"No track is included until it is settled."),
}
SHIELD_STATUS = {
@@ -179,3 +180,65 @@ def length(km, style="inline", mi=None, measured=False):
mi_text = f"{fmt_int(mi)} mi" if whole or mi >= 100 else f"{mi:,.1f} mi"
return Markup(f'<span class="len len--{style}"><span class="len__km">{esc(km_text)}</span>'
f'<span class="len__mi">{esc(mi_text)}</span></span>')
# Hiker facts ([hike] table) -------------------------------------------------
M_PER_FT = 0.3048
TERRAIN = {
"alpine": "Alpine", "forest": "Forest", "desert": "Desert", "coast": "Coast",
"prairie": "Prairie", "canyon": "Canyon", "tundra": "Tundra", "lakes": "Lakes",
"farmland": "Farmland",
}
# The [hike] fields a [[hike.source]] may name in `facts`, in plain words.
HIKE_FACTS = {
"summary": "description", "official_url": "official site", "start": "start", "end": "end",
"shape": "shape", "days": "time", "season": "season", "months": "season", "travel": "walking", "high_point": "high point",
"high_point_m": "high point elevation", "terrain": "terrain", "permit": "permits",
"unfinished": "unfinished sections", "caution": "caution",
}
def _plural(n, unit):
return f"{n} {unit}" if n == 1 else f"{n} {unit}s"
def fmt_days(days):
"""Usual time to walk a trail in one go, in a unit a person would use.
[4, 6] -> "4 to 6 days"; [14, 21] -> "2 to 3 weeks"; [150, 210] -> "5 to 7 months".
Days up to 14, weeks up to 9 weeks (63 days), months beyond. One value, or both
ends the same after rounding: "5 days", "about 3 weeks". "" for no value.
"""
if isinstance(days, (int, float)):
days = [days]
days = [d for d in (days or []) if isinstance(d, (int, float)) and d > 0]
if not days:
return ""
lo, hi = min(days), max(days)
if hi <= 14:
unit, a, b = "day", round(lo), round(hi)
elif hi <= 63:
unit, a, b = "week", max(1, round(lo / 7)), max(1, round(hi / 7))
else:
unit, a, b = "month", max(1, round(lo / 30.44)), max(1, round(hi / 30.44))
if a == b:
return _plural(a, unit) if unit == "day" else "about " + _plural(a, unit)
return f"{a} to {b} {unit}s"
def elevation(m, style="inline"):
"""An elevation in metres and feet; the reader's unit preference decides the order,
with the same len__km / len__mi pair as lengths: "2,025 m (6,644 ft)".
style "stack" sets the first unit large over the second, as lengths do."""
ft = m / M_PER_FT
return Markup(f'<span class="len len--{style}"><span class="len__km">{esc(fmt_int(m))} m</span>'
f'<span class="len__mi">{esc(fmt_int(ft))} ft</span></span>')
def join_names(names):
"""["a"] -> "a"; ["a", "b"] -> "a and b"; ["a", "b", "c"] -> "a, b and c"."""
names = list(names)
if len(names) <= 1:
return "".join(names)
return ", ".join(names[:-1]) + " and " + names[-1]