web/ is a static site generator for the dataset, in Python's standard library only. `python3 web/build.py --out _site` writes a page for each of the 138 records, a finder on the home page with a map of the 85 lines, region and route indexes, and the repository's documents as pages. Each line is offered as the record's GeoJSON and as a GPX simplified to 5 m, with two archives of everything. The site's name and address are set in web/site.toml: Long Hikes, at https://longhikes.org. The dataset keeps its own name. netlify.toml and web/static/_headers configure the Netlify site (content types, download dispositions, caching, a content security policy with no inline script). It is deployed with the Netlify CLI from a local build, because Netlify cannot build from this forge. MapLibre GL JS and the two typefaces are vendored under web/assets/; map tiles come from OpenFreeMap. Tests: python3 -m unittest discover -s web/tests (164). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
c42cfbbe73
commit
abfbeb00bd
77 files changed
+9287
No files matched your search
@@ -0,0 +1 @@
|
||||
"""Data layer and page generator for the long-trails static site."""
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Pieces shared by the home page and the trail pages: record summaries and small components."""
|
||||
import re
|
||||
|
||||
from . import words
|
||||
from .markup import Markup, esc
|
||||
|
||||
|
||||
def trail_path(rec):
|
||||
return f"/trails/{rec['id']}/"
|
||||
|
||||
|
||||
def kind(rec):
|
||||
return rec["derived"]["kind"]
|
||||
|
||||
|
||||
def is_route(rec):
|
||||
return kind(rec) == "route"
|
||||
|
||||
|
||||
def has_line(rec):
|
||||
return rec["derived"]["has_line"]
|
||||
|
||||
|
||||
# A line whose measured length is further than this from the published length
|
||||
# (either way, in percent) needs a length_gap_note (docs/schema.md).
|
||||
LENGTH_LIMIT = 15.0
|
||||
|
||||
|
||||
def line_differs(rec):
|
||||
"""True when the record has a line, the line was measured, and the measured
|
||||
length differs from the published length by more than 15%. The one test of
|
||||
a partial line used by every page."""
|
||||
v = rec.get("verification", {})
|
||||
diff = v.get("difference_percent")
|
||||
return bool(has_line(rec) and v.get("verified") and diff is not None
|
||||
and abs(diff) > LENGTH_LIMIT)
|
||||
|
||||
|
||||
def line_short(rec):
|
||||
"""line_differs, and the measured line is the shorter: the line is partial."""
|
||||
return line_differs(rec) and rec["verification"]["difference_percent"] < 0
|
||||
|
||||
|
||||
def partial_short_text(rec):
|
||||
"""The short form for lists: "Line measures 2.0 km of 1,100 km published"."""
|
||||
v = rec["verification"]
|
||||
word = "of" if v["difference_percent"] < 0 else "against"
|
||||
return (f"Line measures {words.fmt_km1(v['measured_km'])} km {word} "
|
||||
f"{words.fmt_km(rec['length_km'])} km published")
|
||||
|
||||
|
||||
def name(rec):
|
||||
"""The record's name as HTML text, marked with its language when it is not
|
||||
English (web/site.toml [name_lang], copied to derived.name_lang by pages.py).
|
||||
Every place a page shows a record's name as text goes through here."""
|
||||
lang = rec.get("derived", {}).get("name_lang", "")
|
||||
text = esc(rec["name"])
|
||||
return Markup(f'<span lang="{esc(lang)}">{text}</span>') if lang else text
|
||||
|
||||
|
||||
def countries(rec):
|
||||
"""Every country the record touches: its own, and the country of each of its regions.
|
||||
In "US", "CA" order."""
|
||||
found = {rec["country"]} | {words.region_country(c) for c in rec.get("regions", [])}
|
||||
return [c for c in ("US", "CA") if c in found] + sorted(found - {"US", "CA", ""})
|
||||
|
||||
|
||||
_OSM_CREDIT = re.compile(r"(?<!©)(?<!© )(?<!© )OpenStreetMap contributors")
|
||||
|
||||
|
||||
def credit_text(attribution):
|
||||
"""The credit to show and copy: the record's attribution verbatim, with
|
||||
"© " before "OpenStreetMap contributors" where it is not already there."""
|
||||
return _OSM_CREDIT.sub("© OpenStreetMap contributors", attribution or "")
|
||||
|
||||
|
||||
def sentence(text):
|
||||
"""Text ending in a full stop, without doubling one already there."""
|
||||
text = (text or "").rstrip()
|
||||
return text if not text or text.endswith((".", "!", "?")) else text + "."
|
||||
|
||||
|
||||
def policy(rec):
|
||||
return rec.get("route", {}).get("line_policy", "")
|
||||
|
||||
|
||||
def shield_url(rec):
|
||||
shield = rec["derived"]["files"].get("shield")
|
||||
return f"/trails/{rec['id']}/{shield.rsplit('/', 1)[-1]}" if shield else ""
|
||||
|
||||
|
||||
def designated_year(rec):
|
||||
""""National Scenic Trail (2009)" -> "2009"; "" when the designation has no year in brackets."""
|
||||
m = re.search(r"\((\d{4})\)", rec.get("designation", ""))
|
||||
return m.group(1) if m else ""
|
||||
|
||||
|
||||
def short_source(rec):
|
||||
"""A short name for where the included line came from, for lists."""
|
||||
src = rec.get("source", {})
|
||||
if src.get("osm_only"):
|
||||
name = "OpenStreetMap"
|
||||
else:
|
||||
name = re.split(r" \(|, | with ", src.get("line_source", ""))[0]
|
||||
if "OpenStreetMap" in src.get("attribution", "") and "OpenStreetMap" not in name:
|
||||
name += " and OpenStreetMap"
|
||||
return name
|
||||
|
||||
|
||||
def licence_label(rec):
|
||||
src = rec.get("source", {})
|
||||
text = words.label(words.LICENCES, src.get("licence", ""))
|
||||
if "ODbL" in src.get("attribution", "") and src.get("licence") != "ODbL-1.0":
|
||||
text += " and ODbL 1.0"
|
||||
return text
|
||||
|
||||
|
||||
def rich(text):
|
||||
"""Escape record text, setting `backticked` spans (Overpass queries and the like) as code."""
|
||||
parts = esc(text).split("`")
|
||||
if len(parts) % 2 == 0: # unbalanced backticks: leave the text as it is
|
||||
return esc(text)
|
||||
return Markup("".join(f"<code>{p}</code>" if i % 2 else p for i, p in enumerate(parts)))
|
||||
|
||||
|
||||
def absent_reason_short(rec):
|
||||
"""line_absent_reason without the opening "No line is included." (the status already says so)."""
|
||||
reason = rec.get("source", {}).get("line_absent_reason", "")
|
||||
return re.sub(r"^No line 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 line policy of a route."""
|
||||
out = []
|
||||
if is_route(rec):
|
||||
out.append('<span class="tag tag--route">Person-defined route</span>')
|
||||
elif 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))
|
||||
|
||||
|
||||
def policy_chip(value):
|
||||
lab, short = words.label(words.POLICIES, value), words.meaning(words.POLICIES, value)
|
||||
return Markup(f'<span class="policy policy--{esc(value)}" title="Line policy: {esc(short)}">'
|
||||
f'<span class="vh">Line policy: </span>{esc(lab)}</span>')
|
||||
|
||||
|
||||
def logo_img(rec, alt, eager=False):
|
||||
"""The logo <img>: the PNG thumbnail at its real size when there is one (olt/thumbs.py), else the file."""
|
||||
logo = rec["derived"].get("logo_img")
|
||||
src, dims = (logo["src"], f' width="{logo["width"]}" height="{logo["height"]}"') if logo \
|
||||
else (shield_url(rec), "")
|
||||
loading = "" if eager else ' loading="lazy"'
|
||||
return f'<img src="{esc(src)}" alt="{esc(alt)}"{dims}{loading} decoding="async">'
|
||||
|
||||
|
||||
def plate(rec, *, size="", link=False, eager=False, alt=None):
|
||||
"""The logo on a light plate, or a dashed plate with the short name when there is no logo file.
|
||||
|
||||
link: the logo links to the full-size file. eager: not lazy-loaded (the record page header).
|
||||
alt: the image's text; by default "<name> logo" on a sized plate and "" on a list plate.
|
||||
A linked image with alt="" gets its link text from a visually hidden span instead.
|
||||
"""
|
||||
url = shield_url(rec)
|
||||
cls = f"plate plate--{size}" if size else "plate"
|
||||
if url:
|
||||
if alt is None:
|
||||
alt = f"{rec['name']} logo" if size else ""
|
||||
img = logo_img(rec, alt, eager)
|
||||
if link:
|
||||
label = "" if alt else f'<span class="vh">Full-size logo: {name(rec)}</span>'
|
||||
img = f'<a href="{esc(url)}">{img}{label}</a>'
|
||||
return Markup(f'<div class="{cls}">{img}</div>')
|
||||
return Markup(f'<div class="{cls} plate--none" aria-hidden="true"><span>{esc(rec.get("short_name", ""))}</span></div>')
|
||||
|
||||
|
||||
SWATCH_LINE = Markup('<span class="swatch swatch--line" aria-hidden="true"></span>')
|
||||
SWATCH_ROUTE = Markup('<span class="swatch swatch--route" aria-hidden="true"></span>')
|
||||
SWATCH_ALT = Markup('<span class="swatch swatch--alt" aria-hidden="true"></span>')
|
||||
SWATCH_NONE = Markup('<span class="swatch swatch--none" aria-hidden="true"></span>')
|
||||
|
||||
ICON_DOWNLOAD = Markup('<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">'
|
||||
'<path d="M8 1.5v9M4 7l4 4 4-4M2.5 14.5h11" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>')
|
||||
ICON_EXTERNAL = Markup('<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">'
|
||||
'<path d="M6 3H3v10h10v-3M9 2.5h4.5V7M13.5 2.5 7 9" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>')
|
||||
+405
@@ -0,0 +1,405 @@
|
||||
"""Document-backed pages: /sources/, /logos/, /about/, /data/ and sub-pages.
|
||||
|
||||
Markdown goes through olt.md; relative links are rewritten to site pages.
|
||||
Repository paths with no site page become repository links when repo_url
|
||||
is set, and plain text otherwise (never a dead link).
|
||||
"""
|
||||
import collections
|
||||
import os
|
||||
import re
|
||||
|
||||
from . import common, md, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
REAL_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
def read_doc(repo_root, relpath):
|
||||
"""Read a repository document, falling back to this checkout's copy."""
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
path = os.path.join(base, *relpath.split("/"))
|
||||
if os.path.isfile(path):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
return ""
|
||||
|
||||
|
||||
_PAGE_MAP = {
|
||||
"docs/schema.md": "/data/schema/",
|
||||
"schema.md": "/data/schema/",
|
||||
"notice.md": "/logos/",
|
||||
"sources.md": "/sources/",
|
||||
"contributing.md": "/about/",
|
||||
"changelog.md": "/data/changelog/",
|
||||
"readme.md": "/about/",
|
||||
"license": "/licences/LICENSE",
|
||||
"trails.csv": "/data/trails.csv",
|
||||
"trails.json": "/data/trails.json",
|
||||
"index.geojson": "/data/index.geojson",
|
||||
"overview.geojson": "/data/overview.geojson",
|
||||
}
|
||||
|
||||
|
||||
def _classify(href, site):
|
||||
"""Site href for a Markdown destination, or None to drop the link."""
|
||||
if not href or href.startswith(("#", "/", "http://", "https://", "mailto:", "tel:")):
|
||||
return href
|
||||
path, _, frag = href.partition("#")
|
||||
norm = path[2:] if path.startswith("./") else path
|
||||
while norm.startswith("../"):
|
||||
norm = norm[3:]
|
||||
key = norm.lower()
|
||||
if key in _PAGE_MAP:
|
||||
return _PAGE_MAP[key] + (f"#{frag}" if frag else "")
|
||||
if key.startswith("licenses/") and key.endswith(".txt"):
|
||||
return "/licences/" + norm.split("/", 1)[1] + (f"#{frag}" if frag else "")
|
||||
if site.repo_url:
|
||||
return f"{site.repo_url}/blob/main/{norm}" + (f"#{frag}" if frag else "")
|
||||
return None
|
||||
|
||||
|
||||
def make_link_rewrite(site):
|
||||
"""md.render link_rewrite: the site href, or None (md.py then keeps the link's text only)."""
|
||||
return lambda href: _classify(href, site)
|
||||
|
||||
|
||||
def _link_text(html, phrase, url):
|
||||
"""Link each occurrence of phrase in the text of html (not inside a tag or an existing link)."""
|
||||
out, depth = [], 0
|
||||
for part in re.split(r"(<[^>]*>)", html):
|
||||
if part.startswith("<"):
|
||||
if re.match(r"<a[\s>]", part):
|
||||
depth += 1
|
||||
elif part.startswith("</a"):
|
||||
depth = max(0, depth - 1)
|
||||
elif depth == 0 and phrase in part:
|
||||
part = part.replace(phrase, f'<a href="{esc(url)}">{phrase}</a>')
|
||||
out.append(part)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def link_requests(html, site):
|
||||
"""Link the documents' own words asking readers to open an issue or to write
|
||||
to the maintainers, when site.toml says where (repo_url, contact_url).
|
||||
The wording is left as the documents have it; with neither set, nothing changes."""
|
||||
issue = site.issues_url or site.contact_url
|
||||
contact = site.contact_url or site.repo_url
|
||||
if issue:
|
||||
for phrase in ("Open an issue", "open an issue", "opening an issue"):
|
||||
html = _link_text(html, phrase, issue)
|
||||
if contact:
|
||||
for phrase in ("writing to the repository maintainers", "write to the repository maintainers"):
|
||||
html = _link_text(html, phrase, contact)
|
||||
return Markup(html)
|
||||
|
||||
|
||||
def render_doc(text, site, *, heading_offset=0, drop_h1=False):
|
||||
"""Render Markdown to HTML with rewritten links and scrollable tables."""
|
||||
if drop_h1:
|
||||
text = re.sub(r"\A# [^\n]*\n+", "", text, count=1)
|
||||
html = md.render(text, heading_offset=heading_offset,
|
||||
link_rewrite=make_link_rewrite(site))
|
||||
html = html.replace("<table>", '<div class="table-wrap"><table>')
|
||||
html = html.replace("</table>", "</table></div>")
|
||||
return Markup(html)
|
||||
|
||||
|
||||
def sections_map(text):
|
||||
return dict(md.split_sections(text, level=2))
|
||||
|
||||
|
||||
def render_sections(text, site, titles, *, level=2):
|
||||
"""Render named level-2 sections only, each under its own heading."""
|
||||
found = sections_map(text) if level == 2 else {}
|
||||
out = []
|
||||
for title in titles:
|
||||
body = found.get(title)
|
||||
if body is None:
|
||||
continue
|
||||
out.append(md.render(f"## {title}\n\n{body}", link_rewrite=make_link_rewrite(site)))
|
||||
html = "\n".join(out)
|
||||
html = html.replace("<table>", '<div class="table-wrap"><table>')
|
||||
html = html.replace("</table>", "</table></div>")
|
||||
return Markup(html)
|
||||
|
||||
|
||||
def _record_links(recs):
|
||||
"""The records as a link list, one name per line."""
|
||||
return Markup('<ul class="linklist">' + "".join(
|
||||
f'<li><a href="{esc(common.trail_path(r))}">{common.name(r)}</a></li>' for r in recs) + "</ul>")
|
||||
|
||||
|
||||
def _group_by(records, keyfn):
|
||||
groups = collections.defaultdict(list)
|
||||
for r in records:
|
||||
groups[keyfn(r)].append(r)
|
||||
for recs in groups.values():
|
||||
recs.sort(key=lambda r: r["name"].lower())
|
||||
return groups
|
||||
|
||||
|
||||
def sources_page(records, site, repo_root):
|
||||
"""(title, description, body) for /sources/."""
|
||||
by_licence = _group_by(records, lambda r: r.get("source", {}).get("licence", "") or "unknown")
|
||||
by_source = _group_by(records, lambda r: r.get("source", {}).get("line_source", "") or "none (no line included)")
|
||||
by_status = _group_by(records, lambda r: r.get("source", {}).get("status", "") or "none")
|
||||
|
||||
def measured(recs):
|
||||
return sum(1 for r in recs if r.get("verification", {}).get("verified"))
|
||||
|
||||
n_measured = measured(records)
|
||||
status_cells = (f'<div><dt>Line measured</dt><dd>{n_measured}<small>Records whose line was '
|
||||
f'downloaded and measured (verification), whatever its source</small></dd></div>')
|
||||
for key in ("verified", "osm-only", "found", "none"):
|
||||
recs = by_status.get(key, [])
|
||||
k = measured(recs)
|
||||
of_these = (f"; {k} of these measured" if k and k < len(recs) else
|
||||
"; all measured" if k and k == len(recs) and key != "verified" else "")
|
||||
status_cells += (f'<div><dt>Source status: {esc(words.label(words.SOURCE_STATUS, key))}</dt>'
|
||||
f'<dd>{len(recs)}<small>{esc(words.meaning(words.SOURCE_STATUS, key))}{esc(of_these)}</small></dd></div>')
|
||||
other = [k for k in by_status if k not in ("verified", "osm-only", "found", "none")]
|
||||
|
||||
def group_rows(groups, label_of):
|
||||
rows = ""
|
||||
for key in sorted(groups, key=lambda k: (-len(groups[k]), str(k).lower())):
|
||||
recs = groups[key]
|
||||
lines = sum(1 for r in recs if common.has_line(r))
|
||||
rows += (f'<tr><td>{label_of(key)}</td><td class="num">{len(recs)}</td>'
|
||||
f'<td class="num">{lines}</td><td>{_record_links(recs)}</td></tr>')
|
||||
return rows
|
||||
|
||||
def lic_label(k):
|
||||
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 line</th><th scope="col">Trails and routes</th></tr></thead>')
|
||||
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.
|
||||
The source status says where a line was looked for; whether it was measured is counted separately.</p></div>
|
||||
<dl class="tally">{status_cells}</dl>
|
||||
{f'<p class="note">Other source status values: {esc(", ".join(map(str, other)))}.</p>' if other else ""}
|
||||
<div class="doc-block"><h3>By licence</h3><div class="table-wrap"><table>
|
||||
{head.format("Licence")}
|
||||
<tbody>{group_rows(by_licence, lic_label)}</tbody></table></div></div>
|
||||
<div class="doc-block"><h3>By line source</h3><div class="table-wrap"><table>
|
||||
{head.format("Line source")}
|
||||
<tbody>{group_rows(by_source, esc)}</tbody></table></div></div>
|
||||
</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>'
|
||||
f'<p class="page-head__lede">Where the lines 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>')
|
||||
return "Sources", "Where each trail line comes from: licences, line sources and source terms.", Markup(body)
|
||||
|
||||
|
||||
def logos_page(records, site, repo_root):
|
||||
"""(title, description, body) for /logos/."""
|
||||
notice_html = link_requests(render_sections(read_doc(repo_root, "NOTICE.md"), site,
|
||||
["Logos and marks", "Removal"]), site)
|
||||
with_logo = [r for r in sorted(records, key=lambda r: r["name"].lower())
|
||||
if "shield" in r["derived"]["files"]]
|
||||
cards = ""
|
||||
for r in with_logo:
|
||||
sh = r.get("shield", {})
|
||||
src = sh.get("logo_source", "")
|
||||
if src.startswith(("http://", "https://")):
|
||||
src_html = Markup(f'<a href="{esc(src)}">{esc(src)}</a>')
|
||||
elif src:
|
||||
src_html = esc(src)
|
||||
else:
|
||||
src_html = Markup("Not recorded")
|
||||
cards += f"""<li class="logo-card">
|
||||
{common.plate(r, size="lg", link=True, alt="")}
|
||||
<div><h3><a href="{esc(common.trail_path(r))}">{common.name(r)}</a></h3>
|
||||
<dl class="facts"><div><dt>Holder</dt><dd>{esc(sh.get("logo_owner", "") or "Not recorded")}</dd></div>
|
||||
<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>
|
||||
<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}</div></div>
|
||||
<div class="container section"><div class="section-head"><h2>Every logo in the dataset</h2>
|
||||
<p>{len(with_logo)} records include a logo file.</p></div>
|
||||
<ul class="logo-grid">{cards}</ul>
|
||||
<p class="note">No logo file is included for the other records: {counts["no-logo-exists"]} are recorded as
|
||||
having no logo (<code class="raw">no-logo-exists</code>) and {counts["logo-not-found"]} as
|
||||
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)
|
||||
|
||||
|
||||
def about_page(records, site, repo_root):
|
||||
"""(title, description, body) for /about/."""
|
||||
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)
|
||||
contrib = render_doc(read_doc(repo_root, "CONTRIBUTING.md"), site, heading_offset=1)
|
||||
extra = ""
|
||||
if 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>'
|
||||
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)
|
||||
|
||||
|
||||
def _size(out_dir, relpath):
|
||||
path = os.path.join(out_dir, *relpath.split("/"))
|
||||
return words.fmt_bytes(os.path.getsize(path)) if os.path.isfile(path) else "—"
|
||||
|
||||
|
||||
# The bulk files on /data/: (name, what it holds, offered as a download).
|
||||
# trails.json and overview.geojson are what the pages fetch; a browser shows them.
|
||||
BULK_FILES = (
|
||||
("trails.csv", "One row per trail: id, name, country, regions, length, kind, line policy and status.", True),
|
||||
("trails.json", "Every record in full, as JSON, with the derived fields the site builds.", False),
|
||||
("index.geojson", "Every included line, simplified to about 100 m, with id and name.", True),
|
||||
("overview.geojson", "Every included line simplified to about 750 m for the overview map, "
|
||||
"with id, name, kind, country and length.", False),
|
||||
("all-gpx.zip", "Every GPX file (main lines and alternates, simplified to 5 m), as <id>/<file>, "
|
||||
"with each trail's release.txt, trails.csv, SOURCES.md and a README.", True),
|
||||
("all-geojson.zip", "Every full-resolution GeoJSON main line and alternates file, as <id>/<file>, "
|
||||
"with each trail's release.txt, trails.csv, SOURCES.md and a README.", True),
|
||||
)
|
||||
|
||||
|
||||
def _licence_text_url(licence, repo_root):
|
||||
"""Where to read a licence: the copy under /licences/, else the licence's own page, else /sources/."""
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
if os.path.isfile(os.path.join(base, "LICENSES", f"{licence}.txt")):
|
||||
return f"/licences/{licence}.txt"
|
||||
return words.LICENCE_URLS.get(licence, "/sources/")
|
||||
|
||||
|
||||
def line_licence_rows(records, repo_root):
|
||||
"""(what, terms, text URL) for each licence the included lines carry, from the records."""
|
||||
by_licence = _group_by([r for r in records if common.has_line(r)],
|
||||
lambda r: r.get("source", {}).get("licence", "") or "unknown")
|
||||
rows = []
|
||||
for lic in sorted(by_licence, key=lambda k: (-len(by_licence[k]), k.lower())):
|
||||
recs = by_licence[lic]
|
||||
label = words.label(words.LICENCES, lic)
|
||||
n = len(recs)
|
||||
what = f"Lines licensed {esc(label)}: {n} record{'s' if n != 1 else ''}"
|
||||
if n <= 3:
|
||||
links = ", ".join(f'<a href="{esc(common.trail_path(r))}">{common.name(r)}</a>' for r in recs)
|
||||
what += f" ({links})"
|
||||
what = Markup(what)
|
||||
terms = Markup(f'{esc(label)} <code class="raw">{esc(lic)}</code>; credit as named in each record and its release.txt')
|
||||
rows.append((what, terms, _licence_text_url(lic, repo_root)))
|
||||
return rows
|
||||
|
||||
|
||||
def data_page(records, site, repo_root, out_dir):
|
||||
"""(title, description, body) for /data/."""
|
||||
rows = ""
|
||||
for name, what, download in BULK_FILES:
|
||||
dl = f' download="{esc(name)}"' if download else ""
|
||||
rows += (f'<tr><td><a href="/data/{esc(name)}"{dl}>/data/{esc(name)}</a></td>'
|
||||
f'<td>{esc(what)}</td><td class="num">{esc(_size(out_dir, "data/" + name))}</td></tr>')
|
||||
per_trail = [
|
||||
("<id>.geojson", "The main line at full resolution, as published in the dataset."),
|
||||
("<id>.gpx", "The main line simplified to 5 m, for GPS devices. No elevation."),
|
||||
("<id>-alternates.geojson / .gpx", "Alternate and connector lines, where the source serves them separately."),
|
||||
("<id>-<source>.geojson", "One source's own extract, where a line combines sources."),
|
||||
("map.json", "The line simplified to 30 m for the trail page map (GeoJSON)."),
|
||||
("trail.toml", "The record itself: source, licence, verification, logo and route details."),
|
||||
("release.txt", "The source, licence and date the line files came from, where a line is included."),
|
||||
("shield.svg / shield.png", "The trail logo, where one is included. Not licensed; see Logos."),
|
||||
("shield-thumb.png", "A copy of a PNG logo no larger than 256 px, for the lists."),
|
||||
]
|
||||
prow = "".join(f'<tr><td><code>{esc(n)}</code></td><td>{esc(w)}</td></tr>' for n, w in per_trail)
|
||||
lic_rows = [
|
||||
("Records, documents and compiled index", "CC0-1.0 (public domain)", '/licences/LICENSE'),
|
||||
("Tools in tools/", "MIT", '/licences/MIT.txt'),
|
||||
("Each trail line", "Keeps its source's terms, stated in its record; see Sources", '/sources/'),
|
||||
("Lines from OpenStreetMap", "ODbL-1.0; credit © OpenStreetMap contributors", '/licences/ODbL-1.0.txt'),
|
||||
*line_licence_rows(records, repo_root),
|
||||
("Trail logos", "Not licensed; belong to their holders, shown only to identify each trail", '/logos/'),
|
||||
]
|
||||
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>
|
||||
<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>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">File</th><th scope="col">What it holds</th><th scope="col">Size</th></tr></thead>
|
||||
<tbody>{rows}</tbody></table></div>
|
||||
<p class="prose">Each line in the archives keeps its source’s terms and needs its source’s
|
||||
credit, as given in the trail’s release.txt; trails.csv gives each record’s licence too.</p>
|
||||
<div class="doc-block"><h2>Per-trail files</h2>
|
||||
<p class="prose">Every record has a stable directory. Replace <code><id></code> with a record id
|
||||
(for example <code>long-trail</code>): <code>/trails/<id>/<id>.geojson</code>,
|
||||
<code>/trails/<id>/<id>.gpx</code>, <code>/trails/<id>/<id>-alternates.geojson</code> (and <code>.gpx</code>),
|
||||
<code>/trails/<id>/map.json</code>, <code>/trails/<id>/trail.toml</code> and
|
||||
<code>/trails/<id>/release.txt</code>. The trail page is <code>/trails/<id>/</code>.
|
||||
Line files exist only where the record includes a line; the record says why when it does not.</p>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">File under /trails/<id>/</th><th scope="col">What it holds</th></tr></thead>
|
||||
<tbody>{prow}</tbody></table></div></div>
|
||||
<div class="doc-block"><h2>Licences</h2>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">What</th><th scope="col">Terms</th><th scope="col">Text</th></tr></thead>
|
||||
<tbody>{lrow}</tbody></table></div>
|
||||
<p class="prose">Licence texts: <a href="/licences/LICENSE">CC0-1.0 (LICENSE)</a>,
|
||||
<a href="/licences/CC0-1.0.txt">CC0-1.0.txt</a>, <a href="/licences/MIT.txt">MIT.txt</a>,
|
||||
<a href="/licences/CC-BY-4.0.txt">CC-BY-4.0.txt</a>, <a href="/licences/ODbL-1.0.txt">ODbL-1.0.txt</a>.</p></div>
|
||||
<div class="doc-block"><h2>Reference</h2><ul class="linklist doc-links">
|
||||
<li><a href="/data/schema/">Record schema</a><small>Every field of trail.toml</small></li>
|
||||
<li><a href="/data/changelog/">Changelog</a><small>What changed, release by release</small></li>
|
||||
<li><a href="/sources/">Sources</a><small>Each source, its terms and the trails that use it</small></li>
|
||||
</ul></div>
|
||||
</div>"""
|
||||
return "Data", "Bulk downloads, stable per-trail file URLs, the record schema and licences.", Markup(body)
|
||||
|
||||
|
||||
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>
|
||||
<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>
|
||||
<div class="container section"><div class="prose doc">{doc_html}</div></div>"""
|
||||
return "Record schema", "Every field of a trail record (trail.toml) and what it means.", Markup(body)
|
||||
|
||||
|
||||
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>
|
||||
<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>
|
||||
<div class="container section"><div class="prose doc">{doc_html}</div></div>"""
|
||||
return "Changelog", "What changed in the dataset, release by release.", Markup(body)
|
||||
|
||||
|
||||
def copy_licences(out_dir, repo_root):
|
||||
"""Copy LICENSE and LICENSES/*.txt to /licences/. Returns file names copied."""
|
||||
import shutil
|
||||
dest = os.path.join(out_dir, "licences")
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
copied = []
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
lic = os.path.join(base, "LICENSE")
|
||||
if os.path.isfile(lic):
|
||||
shutil.copyfile(lic, os.path.join(dest, "LICENSE"))
|
||||
copied.append("LICENSE")
|
||||
break
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
d = os.path.join(base, "LICENSES")
|
||||
if os.path.isdir(d):
|
||||
for name in sorted(os.listdir(d)):
|
||||
if name.endswith(".txt"):
|
||||
shutil.copyfile(os.path.join(d, name), os.path.join(dest, name))
|
||||
copied.append(name)
|
||||
break
|
||||
return copied
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
"""Line geometry helpers: reading GeoJSON, length, bbox, simplification, GPX.
|
||||
|
||||
Python 3 standard library only. A "part" is a list of coordinates, each
|
||||
[lon, lat] or [lon, lat, ele]; a line is a list of parts.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
from xml.sax.saxutils import escape, quoteattr
|
||||
|
||||
EARTH_R = 6371008.8 # metres
|
||||
LICENCE_URLS = {
|
||||
"us-gov-public-domain": "https://www.usa.gov/government-works",
|
||||
"CC-BY-4.0": "https://creativecommons.org/licenses/by/4.0/",
|
||||
"CC-BY": "https://creativecommons.org/licenses/by/4.0/",
|
||||
"ODbL-1.0": "https://opendatacommons.org/licenses/odbl/1-0/",
|
||||
}
|
||||
|
||||
|
||||
def read_parts(path):
|
||||
"""Read a GeoJSON file; return its LineString and MultiLineString parts."""
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return parts_from_geojson(data)
|
||||
|
||||
|
||||
def parts_from_geojson(data):
|
||||
if data.get("type") == "FeatureCollection":
|
||||
geoms = [(f.get("geometry") or {}) for f in data.get("features", [])]
|
||||
elif data.get("type") == "Feature":
|
||||
geoms = [data.get("geometry") or {}]
|
||||
else:
|
||||
geoms = [data]
|
||||
parts = []
|
||||
for geom in geoms:
|
||||
gtype = geom.get("type")
|
||||
if gtype == "LineString":
|
||||
parts.append(geom["coordinates"])
|
||||
elif gtype == "MultiLineString":
|
||||
parts.extend(geom["coordinates"])
|
||||
return [p for p in parts if len(p) >= 2]
|
||||
|
||||
|
||||
def point_count(parts):
|
||||
return sum(len(p) for p in parts)
|
||||
|
||||
|
||||
def length_km(parts):
|
||||
"""Geodesic (haversine) length of all parts, in kilometres."""
|
||||
total = 0.0
|
||||
for coords in parts:
|
||||
lon1, lat1 = math.radians(coords[0][0]), math.radians(coords[0][1])
|
||||
for c in coords[1:]:
|
||||
lon2, lat2 = math.radians(c[0]), math.radians(c[1])
|
||||
a = (math.sin((lat2 - lat1) / 2) ** 2
|
||||
+ math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2)
|
||||
total += 2 * EARTH_R * math.asin(min(1.0, math.sqrt(a)))
|
||||
lon1, lat1 = lon2, lat2
|
||||
return total / 1000.0
|
||||
|
||||
|
||||
def bbox(parts):
|
||||
"""[min lon, min lat, max lon, max lat], or None when there are no points."""
|
||||
xs = [c[0] for p in parts for c in p]
|
||||
ys = [c[1] for p in parts for c in p]
|
||||
if not xs:
|
||||
return None
|
||||
return [min(xs), min(ys), max(xs), max(ys)]
|
||||
|
||||
|
||||
def merge_bbox(boxes):
|
||||
boxes = [b for b in boxes if b]
|
||||
if not boxes:
|
||||
return None
|
||||
return [min(b[0] for b in boxes), min(b[1] for b in boxes),
|
||||
max(b[2] for b in boxes), max(b[3] for b in boxes)]
|
||||
|
||||
|
||||
def _gap_m(a, b):
|
||||
"""Approximate distance in metres between two [lon, lat] points."""
|
||||
dx = (a[0] - b[0]) * math.cos(math.radians((a[1] + b[1]) / 2))
|
||||
return math.hypot(dx, a[1] - b[1]) * math.pi / 180.0 * EARTH_R
|
||||
|
||||
|
||||
def join_parts(parts, gap_m=100.0):
|
||||
"""Chain parts whose end points lie within gap_m of each other.
|
||||
|
||||
Greedy: each chain grows at its tail, then at its head, taking the nearest
|
||||
unused part end each time (a part is reversed when its far end is the
|
||||
near one). Parts that touch nothing stay as they are.
|
||||
|
||||
Ends are bucketed in a metre-scaled grid: longitude is multiplied by the
|
||||
cosine of the highest latitude in the data and both axes use metres, so a
|
||||
grid step is never longer than gap_m on the ground. A fixed step in
|
||||
degrees would miss joins at high latitude, where gap_m spans more than one
|
||||
cell of longitude; here the neighbour scan of plus or minus one cell is
|
||||
correct at any latitude.
|
||||
"""
|
||||
if not parts:
|
||||
return []
|
||||
cell = max(gap_m, 1.0)
|
||||
k = math.pi / 180.0 * EARTH_R
|
||||
max_lat = max(abs(c[1]) for p in parts for c in (p[0], p[-1]))
|
||||
scale = max(math.cos(math.radians(max_lat)), 1e-9) * k
|
||||
|
||||
def cell_of(c):
|
||||
return (math.floor(c[0] * scale / cell), math.floor(c[1] * k / cell))
|
||||
|
||||
grid = {}
|
||||
for i, p in enumerate(parts):
|
||||
for end in (0, 1):
|
||||
c = p[0] if end == 0 else p[-1]
|
||||
grid.setdefault(cell_of(c), []).append((i, end))
|
||||
used = [False] * len(parts)
|
||||
|
||||
def nearest(point):
|
||||
gx, gy = cell_of(point)
|
||||
best = None
|
||||
for x in (gx - 1, gx, gx + 1):
|
||||
for y in (gy - 1, gy, gy + 1):
|
||||
for i, end in grid.get((x, y), ()):
|
||||
if used[i]:
|
||||
continue
|
||||
c = parts[i][0] if end == 0 else parts[i][-1]
|
||||
d = _gap_m(point, c)
|
||||
if d <= gap_m and (best is None or d < best[0]):
|
||||
best = (d, i, end)
|
||||
return best
|
||||
|
||||
out = []
|
||||
for i0, first in enumerate(parts):
|
||||
if used[i0]:
|
||||
continue
|
||||
used[i0] = True
|
||||
chain = list(first)
|
||||
while True: # grow the tail
|
||||
hit = nearest(chain[-1])
|
||||
if hit is None:
|
||||
break
|
||||
_, i, end = hit
|
||||
used[i] = True
|
||||
chain.extend(parts[i] if end == 0 else parts[i][::-1])
|
||||
while True: # grow the head
|
||||
hit = nearest(chain[0])
|
||||
if hit is None:
|
||||
break
|
||||
_, i, end = hit
|
||||
used[i] = True
|
||||
chain[:0] = parts[i][::-1] if end == 0 else parts[i]
|
||||
out.append(chain)
|
||||
return out
|
||||
|
||||
|
||||
def simplify_part(coords, tol_m):
|
||||
"""Douglas-Peucker with an explicit stack; tol_m is in metres.
|
||||
|
||||
Distances are measured on a local equirectangular plane for the segment
|
||||
being tested, scaled by the mean cosine at its two ends. A single scale for
|
||||
a whole part would understate distances when the part runs hundreds of
|
||||
kilometres north to south; taking the cosine per segment bounds the
|
||||
residual error by the change in cosine across that segment.
|
||||
|
||||
When a segment spans enough latitude that its two ends differ in cosine by
|
||||
more than 1%, distances are instead measured in a tangent plane centred on
|
||||
each candidate point (east = (lon - lon_point) * cos(point latitude)).
|
||||
That is the exact local metric, so even a very long north-south segment
|
||||
cannot drop a point whose true distance exceeds the tolerance. Short
|
||||
segments, where the two methods agree to within 1%, use the cheaper shared
|
||||
scale; 1% of the tolerance is a few centimetres at the 5 m GPX tolerance.
|
||||
|
||||
The end points are always kept; only interior points are dropped, and the
|
||||
kept points are the originals. The algorithm is iterative, and the plane
|
||||
origin is folded into precomputed arrays so the inner loop stays cheap
|
||||
enough for parts with hundreds of thousands of points.
|
||||
"""
|
||||
n = len(coords)
|
||||
if n < 3:
|
||||
return list(coords)
|
||||
k = math.pi / 180.0 * EARTH_R
|
||||
lons = [c[0] for c in coords]
|
||||
lats = [c[1] for c in coords]
|
||||
# Metres per degree of longitude (ck) and metres north (ys), per point.
|
||||
ck = [math.cos(math.radians(lat)) * k for lat in lats]
|
||||
ys = [lat * k for lat in lats]
|
||||
tol2 = tol_m * tol_m
|
||||
keep = bytearray(n)
|
||||
keep[0] = keep[n - 1] = 1
|
||||
stack = [(0, n - 1)]
|
||||
while stack:
|
||||
a, b = stack.pop()
|
||||
if b - a < 2:
|
||||
continue
|
||||
la, lb = lons[a], lons[b]
|
||||
dlon = lb - la
|
||||
ya, yb = ys[a], ys[b]
|
||||
dy = yb - ya
|
||||
ca, cb = ck[a], ck[b]
|
||||
# Relative change in cosine across the segment. Below 1% one scale for
|
||||
# the whole segment is as accurate as the tolerance needs (a point
|
||||
# within tol_m of the segment is within a few metres of its latitude,
|
||||
# so the scale error at that point is no larger than this).
|
||||
shared = abs(ca - cb) <= 0.01 * (ca if ca > cb else cb)
|
||||
cm = 0.5 * (ca + cb) if shared else 0.0
|
||||
best, idx = -1.0, -1
|
||||
for i in range(a + 1, b):
|
||||
ci = cm if shared else ck[i]
|
||||
ax = (la - lons[i]) * ci # a, relative to the plane origin
|
||||
ay = ya - ys[i]
|
||||
dx = dlon * ci
|
||||
len2 = dx * dx + dy * dy
|
||||
if len2 == 0.0:
|
||||
d2 = ax * ax + ay * ay
|
||||
else:
|
||||
u = -(ax * dx + ay * dy) / len2
|
||||
if u <= 0.0:
|
||||
d2 = ax * ax + ay * ay
|
||||
elif u >= 1.0:
|
||||
ex, ey = ax + dx, ay + dy
|
||||
d2 = ex * ex + ey * ey
|
||||
else:
|
||||
cross = ax * dy - ay * dx
|
||||
d2 = cross * cross / len2
|
||||
if d2 > best:
|
||||
best, idx = d2, i
|
||||
if best > tol2:
|
||||
keep[idx] = 1
|
||||
stack.append((a, idx))
|
||||
stack.append((idx, b))
|
||||
return [c for c, k_ in zip(coords, keep) if k_]
|
||||
|
||||
|
||||
def simplify(parts, tol_m):
|
||||
return [simplify_part(p, tol_m) for p in parts]
|
||||
|
||||
|
||||
def round_coords(parts, decimals):
|
||||
"""Round lon and lat (elevation is kept); drop repeated neighbours.
|
||||
|
||||
A part that rounds down to fewer than two distinct points is dropped
|
||||
entirely: a zero-length part is not useful on a map or in a GPX track
|
||||
segment, and keeping two copies of one coordinate would produce one.
|
||||
"""
|
||||
out = []
|
||||
for coords in parts:
|
||||
new = []
|
||||
last = None
|
||||
for c in coords:
|
||||
r = [round(c[0], decimals), round(c[1], decimals)] + list(c[2:])
|
||||
key = (r[0], r[1])
|
||||
if key != last:
|
||||
new.append(r)
|
||||
last = key
|
||||
if len(new) >= 2:
|
||||
out.append(new)
|
||||
return out
|
||||
|
||||
|
||||
def has_elevation(parts):
|
||||
return any(len(c) > 2 for p in parts for c in p)
|
||||
|
||||
|
||||
def _num(v):
|
||||
"""Plain decimal text (no exponent, as GPX requires) for a number."""
|
||||
text = f"{float(v):.8f}".rstrip("0").rstrip(".")
|
||||
return "0" if text in ("", "-0") else text
|
||||
|
||||
|
||||
def gpx_text(parts, name, url="", attribution="", licence="", licence_text="",
|
||||
creator="long-trails dataset"):
|
||||
"""GPX 1.1 with one <trk> and one <trkseg> per part."""
|
||||
desc = []
|
||||
if attribution:
|
||||
desc.append(f"Attribution: {attribution}")
|
||||
if licence_text:
|
||||
desc.append(f"Licence: {licence_text}")
|
||||
elif licence:
|
||||
desc.append(f"Licence: {licence}")
|
||||
out = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
f'<gpx version="1.1" creator={quoteattr(creator)} '
|
||||
'xmlns="http://www.topografix.com/GPX/1/1">',
|
||||
"<metadata>",
|
||||
f"<name>{escape(name)}</name>",
|
||||
]
|
||||
if desc:
|
||||
out.append(f"<desc>{escape(' '.join(desc))}</desc>")
|
||||
if attribution:
|
||||
out.append(f"<copyright author={quoteattr(attribution)}>")
|
||||
if licence in LICENCE_URLS:
|
||||
out.append(f"<license>{escape(LICENCE_URLS[licence])}</license>")
|
||||
out.append("</copyright>")
|
||||
if url:
|
||||
out.append(f"<link href={quoteattr(url)}/>")
|
||||
out.append("</metadata>")
|
||||
out.append("<trk>")
|
||||
out.append(f"<name>{escape(name)}</name>")
|
||||
for coords in parts:
|
||||
out.append("<trkseg>")
|
||||
for c in coords:
|
||||
head = f'<trkpt lat="{_num(c[1])}" lon="{_num(c[0])}"'
|
||||
if len(c) > 2:
|
||||
out.append(f"{head}><ele>{_num(c[2])}</ele></trkpt>")
|
||||
else:
|
||||
out.append(f"{head}/>")
|
||||
out.append("</trkseg>")
|
||||
out.append("</trk>")
|
||||
out.append("</gpx>")
|
||||
return "\n".join(out) + "\n"
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
"""The home page: what the site is, the overview map, and the trail finder with every record.
|
||||
|
||||
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.
|
||||
"""
|
||||
import collections
|
||||
import math
|
||||
import re
|
||||
|
||||
from . import common, 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.
|
||||
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."""
|
||||
longest = max((r["length_km"] for r in records), default=0)
|
||||
steps = list(LENGTH_STEPS)
|
||||
if longest > steps[-1]:
|
||||
magnitude = 10 ** int(math.floor(math.log10(longest)))
|
||||
steps.append(int(math.ceil(longest / magnitude) * magnitude))
|
||||
return steps
|
||||
|
||||
|
||||
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."""
|
||||
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
|
||||
return c
|
||||
|
||||
|
||||
def overview_bbox(records):
|
||||
"""data-bbox attribute: the extent of every line, 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 ""
|
||||
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 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.
|
||||
|
||||
level: the heading level of the record's name. extra: HTML placed last in the row.
|
||||
"""
|
||||
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">·</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}Line{policy}</span>'
|
||||
f'{partial_note}'
|
||||
f'<span class="line__detail">GeoJSON, GPX</span>'
|
||||
f'<span class="line__detail">{esc(common.short_source(rec))} · {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 line: </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()
|
||||
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)}"')
|
||||
h = f"h{level}"
|
||||
return f"""<li class="entry"{data}>
|
||||
{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>
|
||||
<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>Line</dt><dd class="line line--{"yes" if common.has_line(rec) else "no"}">{line}</dd></div>
|
||||
</dl>{note}{extra}
|
||||
</li>"""
|
||||
|
||||
|
||||
def _length_options(steps, selected_any_last):
|
||||
opts = [f'<option value="{km}">{km:,} km · {words.fmt_int(words.km_to_mi(km))} mi</option>'
|
||||
for km in steps]
|
||||
if selected_any_last:
|
||||
return "".join(opts[1:]) + '<option value="" selected>Any</option>'
|
||||
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 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])
|
||||
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">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="check">
|
||||
<input type="checkbox" name="line">
|
||||
<span class="check__text">Has a downloadable line <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 line 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>
|
||||
</div>
|
||||
</details>
|
||||
</form>"""
|
||||
|
||||
|
||||
# The length strip's ticks (style.css .loglen): 100, 1,000 and 10,000 km.
|
||||
SCALE_KM = (100, 1000, 10000)
|
||||
|
||||
|
||||
def list_head():
|
||||
"""The column head over a list. The scale ticks follow the reader's unit preference
|
||||
with the same len__km / len__mi pair the lengths use."""
|
||||
ticks = []
|
||||
for i, km in enumerate(SCALE_KM):
|
||||
unit = " km" if i == len(SCALE_KM) - 1 else ""
|
||||
mi_unit = " mi" if i == len(SCALE_KM) - 1 else ""
|
||||
ticks.append(f'<span><span class="len__km">{km:,}{unit}</span>'
|
||||
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>Line</span>
|
||||
</div>"""
|
||||
|
||||
|
||||
UNITS_TOGGLE = """<fieldset class="results-units">
|
||||
<legend class="vh">Lengths</legend>
|
||||
<div class="seg seg--small">
|
||||
<label><input type="radio" name="units-list" value="km" checked><span>km</span></label>
|
||||
<label><input type="radio" name="units-list" value="mi"><span>mi</span></label>
|
||||
</div>
|
||||
</fieldset>"""
|
||||
|
||||
SORT_SELECT = """<label class="results-sort">Sort
|
||||
<select class="select" id="sort" name="sort">
|
||||
<option value="name">Name, A to Z</option>
|
||||
<option value="long">Longest first</option>
|
||||
<option value="short">Shortest first</option>
|
||||
</select>
|
||||
</label>"""
|
||||
|
||||
|
||||
def key():
|
||||
return f"""<ul class="key" aria-label="Key to the list">
|
||||
<li>{common.SWATCH_LINE}Line in the dataset</li>
|
||||
<li>{common.SWATCH_NONE}Record only; the note says why</li>
|
||||
<li>Route line policy:
|
||||
{common.policy_chip("open")} {common.policy_chip("sold")} {common.policy_chip("withheld")} {common.policy_chip("unclear")}
|
||||
</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.
|
||||
|
||||
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.
|
||||
"""
|
||||
if groups is None:
|
||||
groups = [(None, recs, None)]
|
||||
total = sum(len(g[1]) for g in groups)
|
||||
noun = "record" if total == 1 else "records"
|
||||
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)
|
||||
if heading:
|
||||
lists += f'\n <h3 class="results__group">{heading}</h3>'
|
||||
list_id = ' id="entries"' if finder else ""
|
||||
lists += f'\n <ol class="entries"{list_id}>\n{rows}\n </ol>'
|
||||
if finder:
|
||||
count = (f'<p class="results-count" id="results-count" role="status">'
|
||||
f'<strong>{total}</strong> of {total} {noun}</p>')
|
||||
tools = SORT_SELECT + "\n " + UNITS_TOGGLE
|
||||
empty = """
|
||||
<div class="empty-state" id="empty-state" hidden>
|
||||
<p><strong>No records match these filters.</strong></p>
|
||||
<button class="button button--quiet" type="button" data-reset>Clear search and filters</button>
|
||||
</div>"""
|
||||
else:
|
||||
count = f'<p class="results-count"><strong>{total}</strong> {noun}</p>'
|
||||
tools = UNITS_TOGGLE
|
||||
empty = ""
|
||||
return Markup(f"""<div class="results">
|
||||
<div class="results-head">
|
||||
{count}
|
||||
<div class="results-tools">
|
||||
{tools}
|
||||
</div>
|
||||
</div>
|
||||
{key()}
|
||||
{list_head()}{lists}{empty}
|
||||
</div>""")
|
||||
|
||||
|
||||
def render(records, site):
|
||||
"""The home page body (HTML) for every record."""
|
||||
c = counts(records)
|
||||
recs = sorted(records, key=sort_name)
|
||||
total = c["total"]
|
||||
lede = (f"A record for each of {total} long trails and routes, as a rule 50 miles (80 km) or more: "
|
||||
"what it is, how long it is, who publishes it, and on what terms its line may be passed on. "
|
||||
"Where the terms allow, download the line as GeoJSON or GPX.")
|
||||
return f"""<section class="hero" aria-labelledby="hero-title">
|
||||
<div class="container hero__inner">
|
||||
<p class="kicker">A public dataset · United States and Canada</p>
|
||||
<h1 id="hero-title">{esc(site.tagline)}</h1>
|
||||
<p class="hero__lede">{lede}</p>
|
||||
<p class="hero__caveat">This is a dataset, not a navigation product. Lines vary in quality, some trails are unfinished, and some records have no line at all; each of those says why.</p>
|
||||
<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 line</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>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section" aria-labelledby="map-title">
|
||||
<div class="container">
|
||||
<div class="section-head">
|
||||
<h2 id="map-title">Every line in the dataset</h2>
|
||||
<p>{c["line"]} lines, simplified for display. Select a line 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 line 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>Lines are simplified to about 750 m here; each keeps the credit and licence named on its page. Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section" 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 line</p>
|
||||
</div>
|
||||
{finder_form(c, length_steps(records))}
|
||||
{results(recs, finder=True)}
|
||||
</div>
|
||||
</section>"""
|
||||
@@ -0,0 +1,227 @@
|
||||
"""The shared page frame: <head>, header and navigation, footer.
|
||||
|
||||
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 += f'<div class="container prose">...{esc(some_text)}...</div>'
|
||||
html = layout("Regions", body, path="/regions/", description="Long trails by region.")
|
||||
write_page(out_dir, "/regions/", html)
|
||||
|
||||
`path` is the page's own site path; it sets the canonical link (when
|
||||
site.toml has base_url) and marks the current item in the navigation.
|
||||
Everything else on the page comes from style.css and app.js; no inline
|
||||
scripts or styles (the Content-Security-Policy forbids them).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
from . import site as site_settings
|
||||
from .markup import Markup, attrs, esc, json_block
|
||||
|
||||
NAV = (
|
||||
("Trails", "/"),
|
||||
("Regions", "/regions/"),
|
||||
("Routes", "/routes/"),
|
||||
("Sources", "/sources/"),
|
||||
("Logos", "/logos/"),
|
||||
("About", "/about/"),
|
||||
("Data", "/data/"),
|
||||
)
|
||||
|
||||
FONT_PRELOADS = (
|
||||
"/assets/fonts/source-serif-4-latin.woff2",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-400-latin.woff2",
|
||||
)
|
||||
MAPLIBRE_CSS = "/assets/vendor/maplibre-gl/maplibre-gl.css"
|
||||
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)
|
||||
|
||||
|
||||
def header(path, site):
|
||||
items = "".join(
|
||||
f'<li><a href="{esc(href)}"{attrs(aria_current="page" if path == href else ("true" if _current(path, href) else None))}>'
|
||||
f"{esc(text)}</a></li>"
|
||||
for text, href in NAV)
|
||||
return Markup(f"""<header class="site-header">
|
||||
<div class="container site-header__inner">
|
||||
<a class="wordmark" href="/"><span class="wordmark__blaze" aria-hidden="true"></span>{esc(site.name)}</a>
|
||||
<nav aria-label="Main"><ul class="nav">{items}</ul></nav>
|
||||
</div>
|
||||
</header>""")
|
||||
|
||||
|
||||
def footer(site):
|
||||
report = (f'<li><a href="{esc(site.issues_url)}">Report an error in a record</a></li>'
|
||||
if site.issues_url else "")
|
||||
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: lines vary in quality, some trails are unfinished, and some records have no line at all. Check a trail’s own record before using its line.</p>
|
||||
<p>The records are public domain (CC0-1.0). Each line keeps the terms of its source, named on its page. Lines from OpenStreetMap are © 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>
|
||||
<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 line, simplified</li>
|
||||
<li><a href="/sources/">Sources and their terms</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<nav aria-labelledby="footer-project">
|
||||
<h2 id="footer-project">Project</h2>
|
||||
<ul>
|
||||
<li><a href="/about/">About {esc(site.name)}</a></li>
|
||||
<li><a href="/logos/">Logos and removal requests</a></li>
|
||||
{report}
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="site-footer__prefs">
|
||||
<fieldset class="field">
|
||||
<legend>Theme</legend>
|
||||
<div class="seg">
|
||||
<label><input type="radio" name="theme" value="auto" checked><span>Auto</span></label>
|
||||
<label><input type="radio" name="theme" value="light"><span>Light</span></label>
|
||||
<label><input type="radio" name="theme" value="dark"><span>Dark</span></label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="field">
|
||||
<legend>Lengths</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>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
</div>
|
||||
<div class="site-footer__base">
|
||||
<div class="container">Base maps: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.</div>
|
||||
</div>
|
||||
</footer>""")
|
||||
|
||||
|
||||
def _ld_json_block(obj):
|
||||
text = json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||
text = text.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
|
||||
return Markup(f'<script type="application/ld+json">{text}</script>')
|
||||
|
||||
|
||||
def layout(title, body, *, path, description="", maps=False, scripts=(), data=None, site=None, jsonld=None, og_type="website"):
|
||||
"""Return a complete HTML document.
|
||||
|
||||
title the page's own title ("Arizona National Scenic Trail"); the site
|
||||
name is appended. Empty for the home page: "<name>: <tagline>".
|
||||
body the page content (HTML, Markup or str), placed inside <main>.
|
||||
path the page's site path, e.g. "/regions/" (canonical link, nav state).
|
||||
description meta description; defaults to the site tagline.
|
||||
maps True to load MapLibre (pages with a .mapfig[data-map]).
|
||||
scripts extra same-origin script URLs, loaded with defer after app.js.
|
||||
data optional object, embedded as <script type="application/json" id="page-data">.
|
||||
site settings (olt.site.Site); defaults to web/site.toml.
|
||||
"""
|
||||
site = site or site_settings.load()
|
||||
full_title = f"{title} · {site.name}" if title else f"{site.name}: {site.tagline}"
|
||||
description = description or site.tagline
|
||||
canonical = site.canonical(path)
|
||||
head = [
|
||||
'<meta charset="utf-8">',
|
||||
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
||||
f"<title>{esc(full_title)}</title>",
|
||||
f'<meta name="description" content="{esc(description)}">',
|
||||
]
|
||||
if canonical:
|
||||
head.append(f'<link rel="canonical" href="{esc(canonical)}">')
|
||||
head += [
|
||||
f'<meta property="og:title" content="{esc(full_title)}">',
|
||||
f'<meta property="og:description" content="{esc(description)}">',
|
||||
f'<meta property="og:type" content="{esc(og_type)}">',
|
||||
f'<meta property="og:site_name" content="{esc(site.name)}">',
|
||||
'<meta name="twitter:card" content="summary">',
|
||||
f'<meta name="twitter:title" content="{esc(full_title)}">',
|
||||
f'<meta name="twitter:description" content="{esc(description)}">',
|
||||
]
|
||||
if canonical:
|
||||
head.append(f'<meta property="og:url" content="{esc(canonical)}">')
|
||||
head.append(f'<meta property="og:image" content="{esc(site.canonical("/assets/favicon.svg"))}">')
|
||||
head.append(f'<meta name="twitter:image" content="{esc(site.canonical("/assets/favicon.svg"))}">')
|
||||
if jsonld is not None:
|
||||
head.append(str(_ld_json_block(jsonld)))
|
||||
head += [
|
||||
'<meta name="color-scheme" content="light dark">',
|
||||
'<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml">',
|
||||
]
|
||||
head += [f'<link rel="preload" href="{f}" as="font" type="font/woff2" crossorigin>' for f in FONT_PRELOADS]
|
||||
if maps:
|
||||
head.append(f'<link rel="stylesheet" href="{MAPLIBRE_CSS}">')
|
||||
head += [
|
||||
'<link rel="stylesheet" href="/assets/style.css">',
|
||||
# Sets the theme and unit preference before first paint (no inline scripts allowed).
|
||||
'<script src="/assets/prefs.js"></script>',
|
||||
]
|
||||
# app.js first: deferred scripts run in order, and the finder and the rest of the
|
||||
# page must not wait for MapLibre (app.js starts the maps when MapLibre arrives).
|
||||
head.append('<script src="/assets/app.js" defer></script>')
|
||||
if maps:
|
||||
head.append(f'<script src="{MAPLIBRE_JS}" defer></script>')
|
||||
head += [f'<script src="{esc(s)}" defer></script>' for s in scripts]
|
||||
data_block = json_block(data, "page-data") if data is not None else ""
|
||||
return f"""<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
{chr(10).join(head)}
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main">Skip to content</a>
|
||||
{header(path, site)}
|
||||
<main id="main">
|
||||
{body}
|
||||
</main>
|
||||
{footer(site)}
|
||||
{data_block}
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def page_head(title, *, kicker="", lede="", crumbs=()):
|
||||
"""A plain page heading block: breadcrumb, kicker, <h1>, lede. For simple pages.
|
||||
|
||||
crumbs is a sequence of (text, href) pairs leading to this page.
|
||||
"""
|
||||
crumb_html = ""
|
||||
if crumbs:
|
||||
items = "".join(f'<li><a href="{esc(h)}">{esc(t)}</a></li>' for t, h in crumbs)
|
||||
crumb_html = (f'<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{items}'
|
||||
f'<li aria-current="page">{esc(title)}</li></ol></nav>')
|
||||
kicker_html = f'<p class="kicker">{esc(kicker)}</p>' if kicker else ""
|
||||
lede_html = f'<p class="page-head__lede">{esc(lede)}</p>' if lede else ""
|
||||
return Markup(f"""<div class="page-head">
|
||||
<div class="container">
|
||||
{crumb_html}
|
||||
<header class="titleblock">
|
||||
<div class="titleblock__text">{kicker_html}<h1>{esc(title)}</h1>{lede_html}</div>
|
||||
</header>
|
||||
</div>
|
||||
</div>""")
|
||||
|
||||
|
||||
def write_page(out_dir, path, document):
|
||||
"""Write a page for a site path: "/" -> index.html, "/a/b/" -> a/b/index.html, "/404.html" -> 404.html."""
|
||||
rel = path.lstrip("/")
|
||||
if not rel or rel.endswith("/"):
|
||||
rel += "index.html"
|
||||
dest = os.path.join(out_dir, *rel.split("/"))
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
with open(dest, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(document)
|
||||
return dest
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Small HTML helpers: escaping, attributes, joining. Standard library only.
|
||||
|
||||
Write page templates as f-strings and pass every value that comes from data
|
||||
through esc() (text and attribute values alike). Strings that are already HTML
|
||||
are Markup; esc() leaves them alone, so helpers can return Markup and be
|
||||
dropped into other templates without double escaping.
|
||||
"""
|
||||
import html
|
||||
import json
|
||||
|
||||
|
||||
class Markup(str):
|
||||
"""A string that is already HTML and must not be escaped again."""
|
||||
|
||||
|
||||
def esc(value):
|
||||
"""Escape text for HTML text or a double-quoted attribute value."""
|
||||
if isinstance(value, Markup):
|
||||
return value
|
||||
if value is None:
|
||||
return Markup("")
|
||||
return Markup(html.escape(str(value), quote=True))
|
||||
|
||||
|
||||
def attrs(**kw):
|
||||
"""Attribute string: attrs(class_="a", data_id="x", hidden=True) -> ' class="a" data-id="x" hidden'.
|
||||
|
||||
A trailing underscore is dropped (class_ -> class) and other underscores
|
||||
become hyphens (aria_label -> aria-label). None and False are left out.
|
||||
"""
|
||||
out = []
|
||||
for key, value in kw.items():
|
||||
if value is None or value is False:
|
||||
continue
|
||||
name = key.rstrip("_").replace("_", "-")
|
||||
out.append(f" {name}" if value is True else f' {name}="{esc(value)}"')
|
||||
return Markup("".join(out))
|
||||
|
||||
|
||||
def join(items, sep=""):
|
||||
"""Join pieces of HTML; plain strings among them are escaped."""
|
||||
return Markup(esc(sep).join(esc(i) for i in items if i not in (None, "")))
|
||||
|
||||
|
||||
def link(href, text, **kw):
|
||||
"""<a href=...>text</a>, with text escaped unless it is Markup."""
|
||||
return Markup(f"<a{attrs(href=href, **kw)}>{esc(text)}</a>")
|
||||
|
||||
|
||||
def json_block(obj, id_):
|
||||
"""A non-executed <script type="application/json"> block (allowed by the site's CSP)."""
|
||||
text = json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||
text = text.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
|
||||
return Markup(f'<script type="application/json" id="{esc(id_)}">{text}</script>')
|
||||
+710
@@ -0,0 +1,710 @@
|
||||
"""Markdown-to-HTML renderer for the site's own documents.
|
||||
|
||||
Covers what README.md, SOURCES.md, NOTICE.md, CONTRIBUTING.md, CHANGELOG.md
|
||||
and docs/schema.md actually use, and little more.
|
||||
|
||||
Supported: ATX headings, paragraphs, unordered (``-``) and ordered (``1.``)
|
||||
lists including nested lists and multi-line items, pipe tables with an
|
||||
alignment row (``---``, ``---:``, ``:---:``), fenced code blocks with an
|
||||
optional language, inline code, bold, italic, ``[text](url)`` links (also in
|
||||
table cells; destinations may hold balanced parentheses or underscores), bare
|
||||
``http(s)://`` URLs and ``<http(s)://...>`` autolinks, ``>`` block quotes,
|
||||
``---``/``***``/``___`` horizontal rules, backslash escapes, and
|
||||
``<!-- ... -->`` comments, which are dropped from the output.
|
||||
|
||||
Not supported: setext headings, reference-style links (a title after an
|
||||
inline link's destination is accepted and dropped), images, footnotes,
|
||||
strikethrough, task lists, indented code blocks, raw HTML passthrough
|
||||
(anything but comments is escaped, never passed through), and emphasis
|
||||
inside code spans or link destinations.
|
||||
"""
|
||||
|
||||
import html as _html
|
||||
import re
|
||||
|
||||
_HEADING_RE = re.compile(r"^(#{1,6})[ \t]*(.*?)[ \t]*$")
|
||||
_CLOSING_HASHES_RE = re.compile(r" +#+$")
|
||||
_LIST_RE = re.compile(r"^([ ]*)([-+*]|\d+[.)])(?:[ \t]+|$)(.*)$")
|
||||
_ALIGN_RE = re.compile(r"^:?-+:?$")
|
||||
_TAG_RE = re.compile(r"<[^>]*>")
|
||||
_LANG_RE = re.compile(r"^[A-Za-z0-9_-]+$")
|
||||
_AUTOLINK_RE = re.compile(r"^<(https?://[^<>\s]+)>")
|
||||
|
||||
_PUNCT = set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
|
||||
|
||||
|
||||
def render(text, *, heading_offset=0, link_rewrite=None):
|
||||
"""Render Markdown to an HTML fragment (no <html>/<body>).
|
||||
|
||||
``heading_offset`` shifts every heading down (``#`` becomes ``<h2>``
|
||||
with ``heading_offset=1``), capped at ``h6``. ``link_rewrite`` is an
|
||||
optional function called with each link's href, returning the href
|
||||
to use in the output, or None to drop the link and keep only its text.
|
||||
"""
|
||||
slugs = {}
|
||||
lines = _strip_comments(text).split("\n")
|
||||
return "\n".join(_blocks(lines, heading_offset, link_rewrite, slugs))
|
||||
|
||||
|
||||
def headings(text):
|
||||
"""Return ``(level, plain text, slug id)`` for each heading, in order.
|
||||
|
||||
The slug is the same id ``render`` puts on the heading element. Slugs
|
||||
are lower-case and hyphenated, and repeats get ``-2``, ``-3`` suffixes.
|
||||
"""
|
||||
found = []
|
||||
slugs = {}
|
||||
in_fence = False
|
||||
for line in _strip_comments(text).split("\n"):
|
||||
if _fence_open(line) is not None or _fence_close(line):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
parsed = _parse_heading(line)
|
||||
if parsed is None:
|
||||
continue
|
||||
level, raw = parsed
|
||||
plain = _plain(raw)
|
||||
found.append((level, plain, _slugify(plain, slugs)))
|
||||
return found
|
||||
|
||||
|
||||
def split_sections(text, level=2):
|
||||
"""Split Markdown into ``(heading text, Markdown body)`` sections.
|
||||
|
||||
A new section starts at each ATX heading with exactly ``level``
|
||||
hashes; its body is the raw Markdown under it, up to the next heading
|
||||
of that level or shallower (deeper headings stay in the body). Text
|
||||
before the first such heading is not part of any section.
|
||||
"""
|
||||
if not 1 <= level <= 6:
|
||||
raise ValueError("level must be 1..6")
|
||||
sections = []
|
||||
title = None
|
||||
body = []
|
||||
in_fence = False
|
||||
for line in _strip_comments(text).split("\n"):
|
||||
if _fence_open(line) is not None or _fence_close(line):
|
||||
in_fence = not in_fence
|
||||
if title is not None:
|
||||
body.append(line)
|
||||
continue
|
||||
parsed = _parse_heading(line) if not in_fence else None
|
||||
if parsed is not None and parsed[0] <= level:
|
||||
if title is not None:
|
||||
sections.append((title, _trim(body)))
|
||||
if parsed[0] == level:
|
||||
title = _plain(parsed[1])
|
||||
body = []
|
||||
else:
|
||||
title = None
|
||||
body = []
|
||||
elif title is not None:
|
||||
body.append(line)
|
||||
if title is not None:
|
||||
sections.append((title, _trim(body)))
|
||||
return sections
|
||||
|
||||
|
||||
def _trim(lines):
|
||||
while lines and not lines[0].strip():
|
||||
del lines[0]
|
||||
while lines and not lines[-1].strip():
|
||||
del lines[-1]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Block layer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _blocks(lines, offset, link_rewrite, slugs):
|
||||
out = []
|
||||
i = 0
|
||||
n = len(lines)
|
||||
while i < n:
|
||||
line = lines[i]
|
||||
if not line.strip():
|
||||
i += 1
|
||||
continue
|
||||
if _fence_open(line) is not None:
|
||||
html, i = _take_fence(lines, i)
|
||||
out.append(html)
|
||||
elif _parse_heading(line) is not None:
|
||||
level, raw = _parse_heading(line)
|
||||
plain = _plain(raw)
|
||||
tag = min(6, level + offset)
|
||||
slug = _slugify(plain, slugs)
|
||||
out.append(f"<h{tag} id=\"{slug}\">"
|
||||
f"{_inline(raw, link_rewrite)}</h{tag}>")
|
||||
i += 1
|
||||
elif _is_hr(line):
|
||||
out.append("<hr>")
|
||||
i += 1
|
||||
elif _parse_quote(line) is not None:
|
||||
quoted = []
|
||||
while i < n and _parse_quote(lines[i]) is not None:
|
||||
quoted.append(_parse_quote(lines[i]))
|
||||
i += 1
|
||||
inner = _blocks(quoted, offset, link_rewrite, slugs)
|
||||
if inner:
|
||||
out.append("<blockquote>\n" + "\n".join(inner)
|
||||
+ "\n</blockquote>")
|
||||
else:
|
||||
out.append("<blockquote>\n</blockquote>")
|
||||
elif _is_list_start(line):
|
||||
html, i = _parse_list(lines, i, offset, link_rewrite, slugs)
|
||||
out.append(html)
|
||||
elif _table_at(lines, i) is not None:
|
||||
html, i = _take_table(lines, i, link_rewrite)
|
||||
out.append(html)
|
||||
else:
|
||||
buf = [line]
|
||||
i += 1
|
||||
while i < n and not _starts_block(lines, i):
|
||||
buf.append(lines[i])
|
||||
i += 1
|
||||
out.append("<p>" + _inline("\n".join(buf).strip(),
|
||||
link_rewrite) + "</p>")
|
||||
return out
|
||||
|
||||
|
||||
def _starts_block(lines, i):
|
||||
line = lines[i]
|
||||
if not line.strip():
|
||||
return True
|
||||
if _fence_open(line) is not None:
|
||||
return True
|
||||
if _parse_heading(line) is not None:
|
||||
return True
|
||||
if _is_hr(line):
|
||||
return True
|
||||
if _parse_quote(line) is not None:
|
||||
return True
|
||||
if _is_list_start(line):
|
||||
return True
|
||||
if _table_at(lines, i) is not None:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_heading(line):
|
||||
"""Return ``(level, raw text)`` for an ATX heading, else None."""
|
||||
body = line.lstrip(" ")
|
||||
if len(line) - len(body) > 3 or not body.startswith("#"):
|
||||
return None
|
||||
match = _HEADING_RE.match(body)
|
||||
if match is None:
|
||||
return None
|
||||
hashes, rest = match.group(1), match.group(2)
|
||||
if body[len(hashes):len(hashes) + 1] not in ("", " ", "\t"):
|
||||
return None
|
||||
rest = _CLOSING_HASHES_RE.sub("", rest).strip()
|
||||
return (len(hashes), rest)
|
||||
|
||||
|
||||
def _fence_open(line):
|
||||
"""Return the info string for a fence opener, else None."""
|
||||
body = line.lstrip(" ")
|
||||
if len(line) - len(body) > 3 or not body.startswith("```"):
|
||||
return None
|
||||
if body[3:4] == "`":
|
||||
return None
|
||||
return body[3:].strip()
|
||||
|
||||
|
||||
def _fence_close(line):
|
||||
stripped = line.strip()
|
||||
return (stripped.startswith("```")
|
||||
and all(ch in " \t" for ch in stripped[3:]))
|
||||
|
||||
|
||||
def _take_fence(lines, i):
|
||||
info = _fence_open(lines[i])
|
||||
lang = info.split()[0] if info.split() else ""
|
||||
buf = []
|
||||
i += 1
|
||||
while i < len(lines) and not _fence_close(lines[i]):
|
||||
buf.append(lines[i])
|
||||
i += 1
|
||||
if i < len(lines):
|
||||
i += 1
|
||||
if lang and _LANG_RE.match(lang):
|
||||
open_tag = f'<pre><code class="language-{lang}">'
|
||||
else:
|
||||
open_tag = "<pre><code>"
|
||||
return open_tag + _html.escape("\n".join(buf)) + "</code></pre>", i
|
||||
|
||||
|
||||
def _is_hr(line):
|
||||
stripped = line.strip()
|
||||
if len(stripped) < 3 or stripped[0] not in "*-_":
|
||||
return False
|
||||
char = stripped[0]
|
||||
return (stripped.count(char) >= 3
|
||||
and all(ch in (char, " ", "\t") for ch in stripped))
|
||||
|
||||
|
||||
def _parse_quote(line):
|
||||
"""Return the line's quote content, else None."""
|
||||
body = line.lstrip(" ")
|
||||
if len(line) - len(body) > 3 or not body.startswith(">"):
|
||||
return None
|
||||
rest = body[1:]
|
||||
if rest.startswith((" ", "\t")):
|
||||
rest = rest[1:]
|
||||
return rest
|
||||
|
||||
|
||||
def _is_list_start(line):
|
||||
match = _LIST_RE.match(line)
|
||||
return match is not None and len(match.group(1)) <= 3
|
||||
|
||||
|
||||
def _parse_list(lines, i, offset, link_rewrite, slugs):
|
||||
first = _LIST_RE.match(lines[i])
|
||||
base = len(first.group(1))
|
||||
ordered = first.group(2)[0].isdigit()
|
||||
start = int(first.group(2)[:-1]) if ordered else 1
|
||||
items = []
|
||||
loose = False
|
||||
n = len(lines)
|
||||
while i < n:
|
||||
match = _LIST_RE.match(lines[i])
|
||||
if (match is None or len(match.group(1)) != base
|
||||
or (match.group(2)[0].isdigit() != ordered)):
|
||||
break
|
||||
content_indent = base + len(match.group(2)) + 1
|
||||
item = [match.group(3)]
|
||||
i += 1
|
||||
while i < n:
|
||||
line = lines[i]
|
||||
if not line.strip():
|
||||
end = i
|
||||
while end < n and not lines[end].strip():
|
||||
end += 1
|
||||
if end >= n:
|
||||
i = end
|
||||
break
|
||||
peek = _LIST_RE.match(lines[end])
|
||||
peek_indent = len(lines[end]) - len(lines[end].lstrip(" "))
|
||||
same_item = peek is not None and peek.group(2)[0].isdigit() == ordered and peek_indent == base
|
||||
if same_item or peek_indent >= content_indent:
|
||||
loose = True
|
||||
item.append("")
|
||||
i = end
|
||||
else:
|
||||
break
|
||||
continue
|
||||
inner = _LIST_RE.match(line)
|
||||
indent = len(line) - len(line.lstrip(" "))
|
||||
if (inner is not None and indent == base
|
||||
and inner.group(2)[0].isdigit() == ordered):
|
||||
break
|
||||
if indent >= content_indent:
|
||||
item.append(line[content_indent:])
|
||||
i += 1
|
||||
else:
|
||||
break
|
||||
while item and not item[-1].strip():
|
||||
item.pop()
|
||||
items.append(item)
|
||||
rendered = []
|
||||
for item in items:
|
||||
sub = _blocks(item, offset, link_rewrite, slugs)
|
||||
if (not loose and sub and sub[0].startswith("<p>")
|
||||
and sub[0].endswith("</p>")):
|
||||
sub = [sub[0][len("<p>"):-len("</p>")]] + sub[1:]
|
||||
rendered.append("<li>" + "\n".join(sub) + "</li>" if sub else "<li></li>")
|
||||
if ordered and start != 1:
|
||||
open_tag, close_tag = f'<ol start="{start}">', "</ol>"
|
||||
elif ordered:
|
||||
open_tag, close_tag = "<ol>", "</ol>"
|
||||
else:
|
||||
open_tag, close_tag = "<ul>", "</ul>"
|
||||
return open_tag + "\n" + "\n".join(rendered) + "\n" + close_tag, i
|
||||
|
||||
|
||||
def _split_cells(line):
|
||||
"""Split a table row into cell segment lists.
|
||||
|
||||
Each cell is a list of ``(is_code, text)`` segments. Pipes inside
|
||||
code spans or escaped as ``\\|`` never split the cell.
|
||||
"""
|
||||
text = line.strip()
|
||||
if text.startswith("|"):
|
||||
text = text[1:]
|
||||
if text.endswith("|") and not text.endswith("\\|"):
|
||||
text = text[:-1]
|
||||
cells = []
|
||||
current = []
|
||||
for is_code, chunk in _split_code(text):
|
||||
if is_code:
|
||||
current.append((True, chunk))
|
||||
else:
|
||||
pieces = re.split(r"(?<!\\)\|", chunk)
|
||||
current.append((False, pieces[0]))
|
||||
for piece in pieces[1:]:
|
||||
cells.append(current)
|
||||
current = [(False, piece)]
|
||||
cells.append(current)
|
||||
for cell in cells:
|
||||
if cell and not cell[0][0]:
|
||||
cell[0] = (False, cell[0][1].lstrip(" \t"))
|
||||
if cell and not cell[-1][0]:
|
||||
cell[-1] = (False, cell[-1][1].rstrip(" \t"))
|
||||
return cells
|
||||
|
||||
|
||||
def _render_cell(cell, link_rewrite):
|
||||
parts = []
|
||||
for is_code, chunk in cell:
|
||||
if is_code:
|
||||
parts.append("<code>" + _html.escape(chunk) + "</code>")
|
||||
else:
|
||||
parts.append(_inline_raw(chunk, link_rewrite))
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _align(cell):
|
||||
text = cell.strip()
|
||||
if text.startswith(":") and text.endswith(":") and len(text) > 2:
|
||||
return "center"
|
||||
if text.endswith(":"):
|
||||
return "right"
|
||||
return "left"
|
||||
|
||||
|
||||
def _table_at(lines, i):
|
||||
"""Return the alignment row's cells if a table starts here."""
|
||||
if "|" not in lines[i] or i + 1 >= len(lines):
|
||||
return None
|
||||
cells = _split_cells(lines[i + 1])
|
||||
if not cells:
|
||||
return None
|
||||
raws = []
|
||||
for cell in cells:
|
||||
raws.append("".join(chunk for _, chunk in cell))
|
||||
if any(not _ALIGN_RE.match(raw.strip()) for raw in raws):
|
||||
return None
|
||||
return raws
|
||||
|
||||
|
||||
def _take_table(lines, i, link_rewrite):
|
||||
header = _split_cells(lines[i])
|
||||
aligns = [_align("".join(chunk for _, chunk in cell))
|
||||
for cell in _split_cells(lines[i + 1])]
|
||||
width = max(len(header), len(aligns))
|
||||
while len(header) < width:
|
||||
header.append([(False, "")])
|
||||
while len(aligns) < width:
|
||||
aligns.append("left")
|
||||
|
||||
def row(cells, tag):
|
||||
out = []
|
||||
scope = ' scope="col"' if tag == "th" else ""
|
||||
for pos in range(width):
|
||||
cell = cells[pos] if pos < len(cells) else [(False, "")]
|
||||
cls = ' class="num"' if aligns[pos] == "right" else ""
|
||||
out.append(f"<{tag}{scope}{cls}>" + _render_cell(cell, link_rewrite)
|
||||
+ f"</{tag}>")
|
||||
return "<tr>" + "".join(out) + "</tr>"
|
||||
|
||||
head = row(header, "th")
|
||||
body_rows = []
|
||||
i += 2
|
||||
while i < len(lines) and lines[i].strip() and "|" in lines[i]:
|
||||
body_rows.append(row(_split_cells(lines[i]), "td"))
|
||||
i += 1
|
||||
html = "<table>\n<thead>\n" + head + "\n</thead>"
|
||||
if body_rows:
|
||||
html += "\n<tbody>\n" + "\n".join(body_rows) + "\n</tbody>"
|
||||
return html + "\n</table>", i
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Comments, slugs, plain text
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _strip_comments(text):
|
||||
"""Drop ``<!-- ... -->`` spans; fenced code blocks are left alone."""
|
||||
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
||||
out = []
|
||||
in_fence = False
|
||||
in_comment = False
|
||||
for line in text.split("\n"):
|
||||
if not in_comment and (_fence_open(line) is not None
|
||||
or _fence_close(line)):
|
||||
in_fence = not in_fence
|
||||
out.append(line)
|
||||
continue
|
||||
if in_fence:
|
||||
out.append(line)
|
||||
continue
|
||||
line, in_comment = _strip_line_comment(line, in_comment)
|
||||
out.append(line)
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _strip_line_comment(line, in_comment):
|
||||
if in_comment:
|
||||
end = line.find("-->")
|
||||
if end < 0:
|
||||
return "", True
|
||||
line = line[end + 3:]
|
||||
in_comment = False
|
||||
while True:
|
||||
start = line.find("<!--")
|
||||
if start < 0:
|
||||
return line, False
|
||||
end = line.find("-->", start + 4)
|
||||
if end < 0:
|
||||
return line[:start], True
|
||||
line = line[:start] + line[end + 3:]
|
||||
|
||||
|
||||
def _plain(raw):
|
||||
"""Inline formatting stripped to plain text (for headings)."""
|
||||
return _html.unescape(_TAG_RE.sub("", _inline(raw, None)))
|
||||
|
||||
|
||||
def _slugify(plain, slugs):
|
||||
base = re.sub(r"[^a-z0-9]+", "-", plain.lower()).strip("-")
|
||||
if not base:
|
||||
base = "section"
|
||||
count = slugs.get(base, 0) + 1
|
||||
slugs[base] = count
|
||||
return base if count == 1 else f"{base}-{count}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Inline layer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _inline(text, link_rewrite):
|
||||
parts = []
|
||||
for is_code, chunk in _split_code(text):
|
||||
if is_code:
|
||||
code = chunk
|
||||
if len(code) > 2 and code[0] in " \t" and code[-1] in " \t" and code.strip(" \t"):
|
||||
code = code[1:-1]
|
||||
parts.append("<code>" + _html.escape(code) + "</code>")
|
||||
else:
|
||||
parts.append(_inline_raw(chunk, link_rewrite))
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _split_code(text):
|
||||
"""Split text into ``(is_code, chunk)`` parts at backtick spans."""
|
||||
parts = []
|
||||
buf = []
|
||||
i = 0
|
||||
n = len(text)
|
||||
while i < n:
|
||||
if text[i] != "`":
|
||||
buf.append(text[i])
|
||||
i += 1
|
||||
continue
|
||||
end = i
|
||||
while end < n and text[end] == "`":
|
||||
end += 1
|
||||
run = end - i
|
||||
close = _find_close(text, end, run)
|
||||
if close < 0:
|
||||
buf.append(text[i:end])
|
||||
i = end
|
||||
else:
|
||||
if buf:
|
||||
parts.append((False, "".join(buf)))
|
||||
buf = []
|
||||
parts.append((True, text[end:close]))
|
||||
i = close + run
|
||||
if buf:
|
||||
parts.append((False, "".join(buf)))
|
||||
return parts
|
||||
|
||||
|
||||
def _find_close(text, start, run):
|
||||
tick = "`" * run
|
||||
pos = text.find(tick, start)
|
||||
while pos >= 0:
|
||||
prev_is_tick = pos > 0 and text[pos - 1] == "`"
|
||||
next_is_tick = pos + run < len(text) and text[pos + run] == "`"
|
||||
if not prev_is_tick and not next_is_tick:
|
||||
return pos
|
||||
pos = text.find(tick, pos + 1)
|
||||
return -1
|
||||
|
||||
|
||||
def _inline_raw(text, link_rewrite):
|
||||
out = []
|
||||
i = 0
|
||||
n = len(text)
|
||||
while i < n:
|
||||
char = text[i]
|
||||
if char == "\\" and i + 1 < n and text[i + 1] in _PUNCT:
|
||||
out.append(_html.escape(text[i + 1]))
|
||||
i += 2
|
||||
elif char == "[":
|
||||
html, i = _parse_link(text, i, link_rewrite)
|
||||
out.append(html)
|
||||
elif char == "<":
|
||||
html, i = _parse_angle(text, i, link_rewrite)
|
||||
out.append(html)
|
||||
elif ((text.startswith("http://", i) or text.startswith("https://", i))
|
||||
and (i == 0 or text[i - 1] in " \t\n('\"")):
|
||||
html, i = _parse_bare(text, i, link_rewrite)
|
||||
out.append(html)
|
||||
elif char in "*_":
|
||||
html, i = _parse_emph(text, i, link_rewrite)
|
||||
out.append(html)
|
||||
elif char == "&":
|
||||
out.append("&")
|
||||
i += 1
|
||||
elif char == ">":
|
||||
out.append(">")
|
||||
i += 1
|
||||
else:
|
||||
out.append(_html.escape(char))
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _parse_link(text, i, link_rewrite):
|
||||
"""Parse ``[label](destination)`` at ``text[i] == '['``."""
|
||||
close = text.find("]", i + 1)
|
||||
if close < 0 or close + 1 >= len(text) or text[close + 1] != "(":
|
||||
return "[", i + 1
|
||||
pos = close + 2
|
||||
while pos < len(text) and text[pos] in " \t":
|
||||
pos += 1
|
||||
if pos < len(text) and text[pos] == "<":
|
||||
end = text.find(">", pos + 1)
|
||||
if end < 0:
|
||||
return "[", i + 1
|
||||
dest, pos = text[pos + 1:end], end + 1
|
||||
else:
|
||||
start = pos
|
||||
depth = 0
|
||||
while pos < len(text):
|
||||
char = text[pos]
|
||||
if char == "(":
|
||||
depth += 1
|
||||
elif char == ")":
|
||||
if depth == 0:
|
||||
break
|
||||
depth -= 1
|
||||
elif char in " \t\n" and depth == 0:
|
||||
break
|
||||
pos += 1
|
||||
dest = text[start:pos]
|
||||
end = pos
|
||||
while end < len(text) and text[end] in " \t":
|
||||
end += 1
|
||||
if end < len(text) and text[end] in "\"'(":
|
||||
quote = ")" if text[end] == "(" else text[end]
|
||||
title_end = text.find(quote, end + 1)
|
||||
if title_end < 0:
|
||||
return "[", i + 1
|
||||
end = title_end + 1
|
||||
if end >= len(text) or text[end] != ")":
|
||||
return "[", i + 1
|
||||
pos = end
|
||||
if pos >= len(text) or text[pos] != ")":
|
||||
return "[", i + 1
|
||||
href = dest.strip()
|
||||
if not href:
|
||||
return "[", i + 1
|
||||
if link_rewrite is not None:
|
||||
href = link_rewrite(href)
|
||||
inner = _inline(text[i + 1:close], link_rewrite)
|
||||
if href is None:
|
||||
return inner, pos + 1
|
||||
return (f'<a href="{_html.escape(href, quote=True)}">{inner}</a>',
|
||||
pos + 1)
|
||||
|
||||
|
||||
def _parse_angle(text, i, link_rewrite):
|
||||
"""Parse ``<https://...>`` autolinks; anything else is escaped."""
|
||||
match = _AUTOLINK_RE.match(text[i:])
|
||||
if match is None:
|
||||
return "<", i + 1
|
||||
url = match.group(1)
|
||||
href = link_rewrite(url) if link_rewrite is not None else url
|
||||
return _anchor(href, url), i + match.end()
|
||||
|
||||
|
||||
def _parse_bare(text, i, link_rewrite):
|
||||
end = i
|
||||
while end < len(text) and text[end] not in " \t\n<>":
|
||||
end += 1
|
||||
url = text[i:end].rstrip(".,;:!?")
|
||||
while url.endswith(")") and url.count("(") < url.count(")"):
|
||||
url = url[:-1]
|
||||
href = link_rewrite(url) if link_rewrite is not None else url
|
||||
return _anchor(href, url), i + len(url)
|
||||
|
||||
|
||||
def _anchor(href, text):
|
||||
"""``<a>`` around escaped text, or the text alone when href is None."""
|
||||
if href is None:
|
||||
return _html.escape(text)
|
||||
return (f'<a href="{_html.escape(href, quote=True)}">'
|
||||
f"{_html.escape(text)}</a>")
|
||||
|
||||
|
||||
def _can_open(char, prev, nxt):
|
||||
if not nxt or nxt in " \t\n":
|
||||
return False
|
||||
return not (char == "_" and prev.isalnum() and nxt.isalnum())
|
||||
|
||||
|
||||
def _can_close(char, prev, nxt):
|
||||
if not prev or prev in " \t\n":
|
||||
return False
|
||||
return not (char == "_" and prev.isalnum() and nxt.isalnum())
|
||||
|
||||
|
||||
def _find_closer(text, pos, char, run_len):
|
||||
i = pos
|
||||
n = len(text)
|
||||
while i < n:
|
||||
if text[i] != char:
|
||||
i += 1
|
||||
continue
|
||||
end = i
|
||||
while end < n and text[end] == char:
|
||||
end += 1
|
||||
run = end - i
|
||||
if run >= run_len and (run_len == 2 or run == 1):
|
||||
prev = text[i - 1] if i > 0 else ""
|
||||
nxt = text[end] if end < n else ""
|
||||
if _can_close(char, prev, nxt):
|
||||
return i
|
||||
i = end
|
||||
return -1
|
||||
|
||||
|
||||
def _parse_emph(text, i, link_rewrite):
|
||||
"""Parse ``**bold**`` or ``*italic*`` at a ``*``/``_`` run."""
|
||||
char = text[i]
|
||||
end = i
|
||||
while end < len(text) and text[end] == char:
|
||||
end += 1
|
||||
run = end - i
|
||||
prev = text[i - 1] if i > 0 else ""
|
||||
for run_len, tag in ((2, "strong"), (1, "em")) if run >= 2 else ((1, "em"),):
|
||||
if run_len == 2 and run < 2:
|
||||
continue
|
||||
nxt = text[i + run_len] if i + run_len < len(text) else ""
|
||||
if not _can_open(char, prev, nxt):
|
||||
continue
|
||||
close = _find_closer(text, i + run_len, char, run_len)
|
||||
if close < 0:
|
||||
continue
|
||||
inner = _inline_raw(text[i + run_len:close], link_rewrite)
|
||||
if not inner.strip():
|
||||
continue
|
||||
return f"<{tag}>{inner}</{tag}>", close + run_len
|
||||
return _html.escape(text[i:end]), end
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Render the site's HTML pages. Called by web/build.py after the data files are written.
|
||||
|
||||
render_site(records, out_dir, repo_root)
|
||||
|
||||
writes:
|
||||
/assets/... web/assets/ copied verbatim (style.css, app.js, fonts, vendor)
|
||||
/index.html home: overview map and the trail finder with every record
|
||||
/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)
|
||||
/404.html not found
|
||||
|
||||
Adding a page elsewhere (regions, sources, ...): build its body as HTML,
|
||||
wrap it with olt.layout.layout() and write it with olt.layout.write_page().
|
||||
See the docstring of olt/layout.py.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from . import 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")
|
||||
|
||||
|
||||
def copy_assets(out_dir, assets_dir=ASSETS_DIR):
|
||||
"""Copy web/assets/ to <out>/assets/, replacing what was there."""
|
||||
dest = os.path.join(out_dir, "assets")
|
||||
if os.path.isdir(dest):
|
||||
shutil.rmtree(dest)
|
||||
shutil.copytree(assets_dir, dest, ignore=shutil.ignore_patterns("README.md", ".*"))
|
||||
|
||||
|
||||
def copy_record_files(rec, out_dir, repo_root):
|
||||
"""Copy trail.toml (and release.txt where present) next to the trail page.
|
||||
|
||||
Also notes on the record what the page needs to know about those files and
|
||||
the map geometry: derived.release and derived.map_bbox.
|
||||
"""
|
||||
tdir = os.path.join(out_dir, "trails", rec["id"])
|
||||
os.makedirs(tdir, exist_ok=True)
|
||||
shutil.copyfile(os.path.join(repo_root, rec["id"], "trail.toml"), os.path.join(tdir, "trail.toml"))
|
||||
release = trail.release_path(repo_root, rec)
|
||||
rec["derived"]["release"] = bool(release)
|
||||
if release:
|
||||
shutil.copyfile(release, os.path.join(tdir, "release.txt"))
|
||||
map_json = os.path.join(tdir, "map.json")
|
||||
if os.path.isfile(map_json):
|
||||
with open(map_json, encoding="utf-8") as f:
|
||||
box = json.load(f).get("bbox")
|
||||
if box:
|
||||
rec["derived"]["map_bbox"] = box
|
||||
|
||||
|
||||
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.")
|
||||
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">
|
||||
<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>
|
||||
</div>"""
|
||||
return layout.layout("Page not found", body, path="/404.html", site=site)
|
||||
|
||||
|
||||
def render_site(records, out_dir, repo_root, site=None):
|
||||
"""Write every HTML page for the given records. Returns the number of pages written."""
|
||||
site = site or site_settings.load()
|
||||
copy_assets(out_dir)
|
||||
pages = 0
|
||||
for rec in records:
|
||||
# Read by common.name() wherever a page shows the record's name as text.
|
||||
rec["derived"]["name_lang"] = site.name_lang.get(rec["id"], "")
|
||||
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)
|
||||
path = f"/trails/{rec['id']}/"
|
||||
layout.write_page(out_dir, path, layout.layout(title, body, path=path, description=description,
|
||||
maps=needs_map, site=site))
|
||||
pages += 1
|
||||
dataset = seo.dataset_jsonld(records, site)
|
||||
body = home.render(records, site)
|
||||
layout.write_page(out_dir, "/", layout.layout("", body, path="/", maps=True, site=site, jsonld=dataset))
|
||||
layout.write_page(out_dir, "/404.html", not_found_page(site))
|
||||
pages += 2
|
||||
|
||||
def add(path, title, description, body_html, *, maps=False, jsonld=None):
|
||||
nonlocal pages
|
||||
layout.write_page(out_dir, path, layout.layout(
|
||||
title, body_html, path=path, description=description, maps=maps, site=site, jsonld=jsonld))
|
||||
pages += 1
|
||||
|
||||
t, d, b = regions.regions_index_page(records, site)
|
||||
add("/regions/", t, d, b)
|
||||
by_slug, _ = regions.collect_regions(records)
|
||||
region_paths = []
|
||||
for slug in sorted(by_slug):
|
||||
t, d, b, needs_map = regions.region_page(slug, records, site)
|
||||
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)
|
||||
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)
|
||||
add("/logos/", t, d, b)
|
||||
t, d, b = docs.about_page(records, site, repo_root)
|
||||
add("/about/", t, d, b)
|
||||
t, d, b = docs.data_page(records, site, repo_root, out_dir)
|
||||
add("/data/", t, d, b, jsonld=dataset)
|
||||
t, d, b = docs.schema_page(site, repo_root)
|
||||
add("/data/schema/", t, d, b)
|
||||
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")
|
||||
return pages
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Load the trail records (one trail.toml per directory) with derived fields."""
|
||||
import os
|
||||
import tomllib
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SHIELD_NAMES = ("shield.svg", "shield.png")
|
||||
|
||||
|
||||
def trail_kind(rec):
|
||||
return rec.get("kind") or "designated"
|
||||
|
||||
|
||||
def trail_status(rec):
|
||||
"""Same rule as the status column of trails.csv (tools/build_index.py)."""
|
||||
return "included" if rec.get("source", {}).get("line_file") else "record-only"
|
||||
|
||||
|
||||
def find_files(root, tid, rec):
|
||||
"""Return the data files that exist for a trail, as paths relative to root."""
|
||||
d = os.path.join(root, tid)
|
||||
files = {}
|
||||
|
||||
def rel(name):
|
||||
return f"{tid}/{name}"
|
||||
|
||||
line_file = rec.get("source", {}).get("line_file") or ""
|
||||
if line_file and os.path.isfile(os.path.join(d, line_file)):
|
||||
files["line"] = rel(line_file)
|
||||
if os.path.isfile(os.path.join(d, "alternates.geojson")):
|
||||
files["alternates"] = rel("alternates.geojson")
|
||||
extracts = {}
|
||||
for name in sorted(os.listdir(d)):
|
||||
if name.startswith("line-") and name.endswith(".geojson"):
|
||||
extracts[name[len("line-"):-len(".geojson")]] = rel(name)
|
||||
if extracts:
|
||||
files["extracts"] = extracts
|
||||
for name in SHIELD_NAMES:
|
||||
if os.path.isfile(os.path.join(d, name)):
|
||||
files["shield"] = rel(name)
|
||||
break
|
||||
return files
|
||||
|
||||
|
||||
def load_record(root, tid):
|
||||
with open(os.path.join(root, tid, "trail.toml"), "rb") as f:
|
||||
rec = tomllib.load(f)
|
||||
length_km = rec.get("length_km", 0)
|
||||
rec["derived"] = {
|
||||
"kind": trail_kind(rec),
|
||||
"has_line": bool(rec.get("source", {}).get("line_file")),
|
||||
"length_mi": int(round(length_km / 1.609344)),
|
||||
"files": find_files(root, tid, rec),
|
||||
"status": trail_status(rec),
|
||||
}
|
||||
return rec
|
||||
|
||||
|
||||
def load_records(root=ROOT):
|
||||
"""Every */trail.toml under root, sorted by id."""
|
||||
ids = sorted(
|
||||
d for d in os.listdir(root)
|
||||
if os.path.isfile(os.path.join(root, d, "trail.toml"))
|
||||
)
|
||||
return [load_record(root, tid) for tid in ids]
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Region pages (/regions/, /regions/<slug>/) and the routes page (/routes/).
|
||||
|
||||
Both list records with home.results(), the same list the home page shows.
|
||||
"""
|
||||
import collections
|
||||
|
||||
from . import common, docs, 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."""
|
||||
by_slug = {}
|
||||
canada_wide = []
|
||||
for r in records:
|
||||
for code in r.get("regions", []):
|
||||
if code == words.ALL_CANADA:
|
||||
canada_wide.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": []})
|
||||
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
|
||||
|
||||
|
||||
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 _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 _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 line 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 lines 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)} line{"s" if len(ids) != 1 else ""} in this region, simplified for display. Select a line for its name.</p>
|
||||
</figcaption>
|
||||
</figure>"""
|
||||
|
||||
|
||||
def regions_index_page(records, site):
|
||||
by_slug, canada_wide = 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 line</th></tr></thead>
|
||||
<tbody>{rows}</tbody></table></div>{extra}</div>"""
|
||||
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></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 lines.", Markup(body)
|
||||
|
||||
|
||||
def region_page(slug, records, site):
|
||||
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)}&line=1">With a line</a>' if lines else "With a line")
|
||||
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>
|
||||
<header class="titleblock"><div class="titleblock__text">
|
||||
<p class="kicker">{esc(words.COUNTRIES[info["country"]])} · {esc(info["code"])}</p>
|
||||
<h1>{esc(info["name"])}</h1>
|
||||
<p class="page-head__lede">{len(recs)} record{"s" if len(recs) != 1 else ""}, {lines} with a downloadable line.</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>Lines in {esc(info["name"])}</h2><p>Only lines 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>
|
||||
{home.results(recs)}
|
||||
<nav class="region-nav" aria-label="Neighbouring regions"><a href="/regions/">All regions</a>{f' · {nav}' if nav else ""}</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)
|
||||
|
||||
|
||||
def route_guides(rec):
|
||||
"""A route's guides, placed last in its list 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"])})'
|
||||
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>'
|
||||
f'{fmt}{price}</li>')
|
||||
if not items:
|
||||
return ""
|
||||
return (f'\n <div class="entry__guides"><p class="route-item__guides-label">Guides</p>'
|
||||
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 line policies">{policy_items}</ol>')
|
||||
|
||||
routes = [r for r in records if common.is_route(r)]
|
||||
by_creator = 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>
|
||||
</div></header></div></div>
|
||||
<div class="container section"><div class="prose doc">{intro}</div>
|
||||
<h2 class="doc-block">The four line 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 line policies and guides.", Markup(body)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Sitemap, robots.txt and the JSON-LD Dataset description."""
|
||||
import html
|
||||
import os
|
||||
|
||||
from . import common
|
||||
|
||||
|
||||
# The files under /data/ listed as the dataset's distribution: (name, media type).
|
||||
DISTRIBUTION = (
|
||||
("trails.csv", "text/csv"),
|
||||
("trails.json", "application/json"),
|
||||
("index.geojson", "application/geo+json"),
|
||||
("overview.geojson", "application/geo+json"),
|
||||
("all-gpx.zip", "application/zip"),
|
||||
("all-geojson.zip", "application/zip"),
|
||||
)
|
||||
|
||||
|
||||
def dataset_jsonld(records, site):
|
||||
"""One schema.org Dataset block for the home page and /data/."""
|
||||
dist = []
|
||||
for name, fmt in DISTRIBUTION:
|
||||
url = site.canonical(f"/data/{name}") or f"/data/{name}"
|
||||
dist.append({"@type": "DataDownload", "name": name, "encodingFormat": fmt, "contentUrl": url})
|
||||
obj = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Dataset",
|
||||
"name": site.name,
|
||||
"description": site.tagline,
|
||||
"license": "https://creativecommons.org/publicdomain/zero/1.0/",
|
||||
"distribution": dist,
|
||||
"variableMeasured": ["length_km", "country", "regions", "source licence"],
|
||||
}
|
||||
if site.base_url:
|
||||
obj["url"] = site.canonical("/")
|
||||
return obj
|
||||
|
||||
|
||||
def sitemap_xml(paths, site):
|
||||
"""sitemap.xml text for site paths; caller checks site.base_url is set."""
|
||||
urls = "".join(
|
||||
f" <url><loc>{html.escape(site.canonical(p), quote=True)}</loc></url>\n"
|
||||
for p in paths)
|
||||
return ('<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
|
||||
f"{urls}</urlset>\n")
|
||||
|
||||
|
||||
def robots_txt(site):
|
||||
lines = ["User-agent: *", "Allow: /", ""]
|
||||
if site.base_url:
|
||||
lines.append(f"Sitemap: {site.canonical('/sitemap.xml')}")
|
||||
return "\n".join(lines).rstrip() + "\n"
|
||||
|
||||
|
||||
def write_seo_files(out_dir, paths, site):
|
||||
"""Write robots.txt always and sitemap.xml only with a base_url."""
|
||||
with open(os.path.join(out_dir, "robots.txt"), "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(robots_txt(site))
|
||||
sitemap = os.path.join(out_dir, "sitemap.xml")
|
||||
if site.base_url:
|
||||
with open(sitemap, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(sitemap_xml(paths, site))
|
||||
elif os.path.isfile(sitemap):
|
||||
os.remove(sitemap) # a stale sitemap with wrong URLs is worse than none
|
||||
|
||||
|
||||
def all_paths(records, region_paths):
|
||||
"""Every indexable page path, in nav order then record pages."""
|
||||
paths = ["/", "/regions/"] + list(region_paths) + [
|
||||
"/routes/", "/sources/", "/logos/", "/about/", "/data/",
|
||||
"/data/schema/", "/data/changelog/"]
|
||||
paths += [common.trail_path(r) for r in sorted(records, key=lambda r: r["id"])]
|
||||
return paths
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Site-wide settings from web/site.toml (name, tagline, base_url, repo_url, contact_url, name_lang)."""
|
||||
import functools
|
||||
import os
|
||||
import tomllib
|
||||
|
||||
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SITE_TOML = os.path.join(WEB_DIR, "site.toml")
|
||||
|
||||
|
||||
class Site:
|
||||
"""The settings every page needs. Build one with load()."""
|
||||
|
||||
def __init__(self, name, tagline, base_url="", repo_url="", contact_url="", name_lang=None):
|
||||
if not name:
|
||||
raise ValueError("site.toml: name must not be empty")
|
||||
self.name = name
|
||||
self.tagline = tagline
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.repo_url = repo_url.rstrip("/")
|
||||
self.contact_url = contact_url.strip()
|
||||
# record id -> language tag of its name ("fr"), for names that are not English
|
||||
self.name_lang = dict(name_lang or {})
|
||||
|
||||
def canonical(self, path):
|
||||
"""Absolute URL of a site path ("/trails/arizona/"), or "" when base_url is unset."""
|
||||
return self.base_url + path if self.base_url else ""
|
||||
|
||||
@property
|
||||
def issues_url(self):
|
||||
"""Where to report an error, or "" when repo_url is unset."""
|
||||
return self.repo_url + "/issues" if self.repo_url else ""
|
||||
|
||||
|
||||
def from_file(path):
|
||||
with open(path, "rb") as f:
|
||||
data = tomllib.load(f)
|
||||
return Site(name=data.get("name", ""), tagline=data.get("tagline", ""),
|
||||
base_url=data.get("base_url", ""), repo_url=data.get("repo_url", ""),
|
||||
contact_url=data.get("contact_url", ""), name_lang=data.get("name_lang", {}))
|
||||
|
||||
|
||||
@functools.cache
|
||||
def load():
|
||||
"""The settings in web/site.toml (read once per process)."""
|
||||
return from_file(SITE_TOML)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""PNG logo thumbnails for the list pages.
|
||||
|
||||
web/thumbs/<id>.png is made by web/tools/make_thumbs.py and committed. The pages
|
||||
step copies it to trails/<id>/shield-thumb.png, and the list pages show that
|
||||
copy at its real pixel size (read from the PNG header; no image library). A
|
||||
PNG logo with no thumbnail falls back to the full-size file, with a warning.
|
||||
SVG logos are not touched.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import sys
|
||||
|
||||
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
THUMB_DIR = os.path.join(WEB_DIR, "thumbs")
|
||||
THUMB_NAME = "shield-thumb.png"
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
|
||||
def png_size(path):
|
||||
"""(width, height) from the IHDR chunk at the start of a PNG file."""
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(24)
|
||||
if len(head) < 24 or head[:8] != PNG_SIGNATURE or head[12:16] != b"IHDR":
|
||||
raise ValueError(f"{path} is not a PNG file")
|
||||
return struct.unpack(">II", head[16:24])
|
||||
|
||||
|
||||
def prepare(rec, out_dir, repo_root, thumb_dir=THUMB_DIR):
|
||||
"""Copy the record's PNG thumbnail into its output directory and set
|
||||
rec["derived"]["logo_img"] = {"src", "width", "height"}, the image the list
|
||||
pages show. Without a PNG logo the key is absent and any old copy is removed.
|
||||
"""
|
||||
tid = rec["id"]
|
||||
tdir = os.path.join(out_dir, "trails", tid)
|
||||
dest = os.path.join(tdir, THUMB_NAME)
|
||||
rec["derived"].pop("logo_img", None)
|
||||
shield = rec["derived"]["files"].get("shield", "")
|
||||
if not shield.endswith(".png"):
|
||||
if os.path.isfile(dest):
|
||||
os.remove(dest)
|
||||
return
|
||||
thumb = os.path.join(thumb_dir, f"{tid}.png")
|
||||
if os.path.isfile(thumb):
|
||||
shutil.copyfile(thumb, dest)
|
||||
path, src = dest, f"/trails/{tid}/{THUMB_NAME}"
|
||||
else:
|
||||
print(f"warning: {tid}: no thumbnail at {os.path.relpath(thumb, WEB_DIR)}; "
|
||||
f"the full-size logo is shown (run web/tools/make_thumbs.py)", file=sys.stderr)
|
||||
if os.path.isfile(dest):
|
||||
os.remove(dest)
|
||||
path, src = os.path.join(repo_root, shield), f"/trails/{tid}/{os.path.basename(shield)}"
|
||||
width, height = png_size(path)
|
||||
rec["derived"]["logo_img"] = {"src": src, "width": width, "height": height}
|
||||
@@ -0,0 +1,737 @@
|
||||
"""One page per record: /trails/<id>/.
|
||||
|
||||
The main sections say what the record says, in plain words. Every field of
|
||||
the record, with its exact value, is in the table at the end of the page
|
||||
(raw_record); the main flow carries no coded values.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
from . import common, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
EXTRACT_SOURCES = {"osm": "OpenStreetMap", "usfs": "USDA Forest Service", "nps": "National Park Service"}
|
||||
GAUGE_MIN, GAUGE_MAX, GAUGE_LIMIT = -40.0, 40.0, common.LENGTH_LIMIT
|
||||
# Download formats in the order a hiker most likely wants them: GPX for devices first.
|
||||
FORMAT_ORDER = ("GPX", "GeoJSON")
|
||||
|
||||
|
||||
# Small building blocks ------------------------------------------------------
|
||||
|
||||
def code(value):
|
||||
return Markup(f'<code class="raw">{esc(value)}</code>')
|
||||
|
||||
|
||||
def fact(label, value, note=""):
|
||||
"""One label/value row of a facts list. note: smaller text under the value.
|
||||
|
||||
Plain-string values and notes are record text: escaped, with `backticked` spans set as code.
|
||||
"""
|
||||
value_html = value if isinstance(value, Markup) else common.rich(value)
|
||||
note_html = f"<small>{note if isinstance(note, Markup) else common.rich(note)}</small>" if note else ""
|
||||
return Markup(f"<div><dt>{esc(label)}</dt><dd>{value_html}{note_html}</dd></div>")
|
||||
|
||||
|
||||
def facts(*rows):
|
||||
rows = [r for r in rows if r]
|
||||
return Markup('<dl class="facts">' + "".join(rows) + "</dl>") if rows else Markup("")
|
||||
|
||||
|
||||
def ext_link(url, text=None):
|
||||
return Markup(f'<a href="{esc(url)}">{esc(text or url)}</a>')
|
||||
|
||||
|
||||
def host(url):
|
||||
netloc = urllib.parse.urlsplit(url).netloc
|
||||
return netloc[4:] if netloc.startswith("www.") else netloc
|
||||
|
||||
|
||||
def yes_no(value):
|
||||
return "Yes" if value else "No"
|
||||
|
||||
|
||||
def block(id_, title, content, extra=""):
|
||||
"""A section of the main column. Its heading carries the id; the section is not a
|
||||
landmark (no aria-labelledby): a page has many of them."""
|
||||
return Markup(f'<section class="block">'
|
||||
f'<h2 id="{id_}">{esc(title)}{extra}</h2>{content}</section>')
|
||||
|
||||
|
||||
def record_text(text, cls=""):
|
||||
return Markup(f'<p class="record-text{(" " + cls) if cls else ""}">{common.rich(text)}</p>')
|
||||
|
||||
|
||||
def restates_no_line(value):
|
||||
"""True for record values that only say there is no line ("none (no line included)")."""
|
||||
text = str(value or "").strip().lower()
|
||||
return text.startswith(("none (no line", "no line included", "no line to measure"))
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
_ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)")
|
||||
|
||||
|
||||
def org_name(text):
|
||||
"""The organisation or person a record names, without the record's own remarks:
|
||||
"Green Mountain Club (publishes the trail); its ArcGIS ..." -> "Green Mountain Club"."""
|
||||
name = _ORG_CUT.split(text or "", maxsplit=1)[0].strip()
|
||||
return name[:1].upper() + name[1:]
|
||||
|
||||
|
||||
# Page head ------------------------------------------------------------------
|
||||
|
||||
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.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)} · {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 ""
|
||||
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>
|
||||
<h1>{common.name(rec)} <span class="titleblock__abbr">{esc(rec.get("short_name", ""))}</span></h1>
|
||||
<p class="titleblock__sub">{sub}</p>
|
||||
</div>
|
||||
</header>
|
||||
{tally(rec)}
|
||||
</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 line", words.length(v["measured_km"], "stack", measured=True),
|
||||
f"{words.fmt_percent(diff)} against published"))
|
||||
else:
|
||||
items.append(("Measured line", Markup('<span class="tally__none">Not measured</span>'),
|
||||
"No line 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(("Line", link, "Licence: " + common.licence_label(rec)))
|
||||
else:
|
||||
items.append(("Line", "Record only", "The reason is given below"))
|
||||
if common.is_route(rec):
|
||||
p = common.policy(rec)
|
||||
items.append(("Line 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>')
|
||||
|
||||
|
||||
# Map or empty frame ---------------------------------------------------------
|
||||
|
||||
def map_figure(rec):
|
||||
src = rec["source"]
|
||||
has_alt = "alternates" in rec["derived"]["files"]
|
||||
route = common.is_route(rec)
|
||||
legend = f'<li>{common.SWATCH_ROUTE if route else common.SWATCH_LINE}Main line</li>'
|
||||
if has_alt:
|
||||
legend += f"<li>{common.SWATCH_ALT}Alternates and connectors</li>"
|
||||
bbox = rec["derived"].get("map_bbox") or rec["derived"].get("bbox")
|
||||
bbox_attr = f' data-bbox="{",".join(str(v) for v in bbox)}"' if bbox else ""
|
||||
credit = common.sentence(common.credit_text(src.get("attribution", "")))
|
||||
return f"""<figure class="mapfig mapfig--detail detail__map" data-map="trail" data-src="/trails/{esc(rec["id"])}/map.json" data-route="{"yes" if route else "no"}"{bbox_attr}>
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true"></span>
|
||||
<div class="map" role="region" aria-label="Map of the {esc(rec["name"])}">
|
||||
<div class="map__fallback"></div>
|
||||
<div class="map__canvas"></div>
|
||||
<p class="map__status" role="status">The map needs JavaScript. Download the line from this page.</p>
|
||||
</div>
|
||||
<span class="mapfig__corner mapfig__corner--se" aria-hidden="true"></span>
|
||||
</div>
|
||||
<figcaption class="mapfig__caption">
|
||||
<ul class="legend" aria-label="Legend">{legend}</ul>
|
||||
<p>Line: {esc(src.get("line_source", ""))}, read {esc(src.get("source_checked", ""))}, drawn simplified to 30 m. Credit: {esc(credit)} Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.</p>
|
||||
</figcaption>
|
||||
</figure>"""
|
||||
|
||||
|
||||
def free_guides(rec):
|
||||
return [g for g in rec.get("guide", []) if g.get("access") == "free"]
|
||||
|
||||
|
||||
def empty_frame(rec):
|
||||
src = rec["source"]
|
||||
reason = src.get("line_absent_reason", "")
|
||||
actions = []
|
||||
if common.is_route(rec):
|
||||
p = common.policy(rec)
|
||||
titles = {
|
||||
"open": "Get the line from the creator",
|
||||
"sold": "The line is sold as a guide",
|
||||
"withheld": "The creator does not publish a line",
|
||||
"unclear": "Whether the line may be shared is not settled",
|
||||
}
|
||||
title = titles.get(p, "No line in this dataset")
|
||||
rule = words.POLICIES.get(p, ("", "", ""))[2]
|
||||
if p == "open" 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>')
|
||||
if not actions:
|
||||
actions.append('<a class="button button--link" href="#guides-title">See where to get the route</a>')
|
||||
elif len(rec.get("guide", [])) > 1:
|
||||
actions.append('<a class="button button--link" href="#guides-title">All guides</a>')
|
||||
else:
|
||||
title = "No line in this dataset"
|
||||
reason = common.absent_reason_short(rec)
|
||||
rule = "A trail may be listed as a record only, with no line, when no line 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’s page {common.ICON_EXTERNAL}</a>')
|
||||
elif src.get("url"):
|
||||
actions.append(f'<a class="button button--link" href="{esc(src["url"])}">'
|
||||
f'The source {common.ICON_EXTERNAL}</a>')
|
||||
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">
|
||||
<div class="mapfig__frame">
|
||||
<span class="mapfig__corner mapfig__corner--nw" aria-hidden="true">No line in this dataset</span>
|
||||
<div class="map map--empty">
|
||||
<div class="map__message">
|
||||
<p class="kicker">Record only</p>
|
||||
<h2 id="noline-title">{esc(title)}</h2>
|
||||
<p>{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 line for this {"route" if common.is_route(rec) else "trail"}, and does not guess one.</p></figcaption>
|
||||
</figure>"""
|
||||
|
||||
|
||||
# Aside: downloads, guides, links --------------------------------------------
|
||||
|
||||
def ordered_downloads(items):
|
||||
"""GPX first, then GeoJSON, then anything else, each keeping its order."""
|
||||
rank = {f: i for i, f in enumerate(FORMAT_ORDER)}
|
||||
return sorted(items, key=lambda d: rank.get(d["format"], len(rank)))
|
||||
|
||||
|
||||
def download_group(rec, label, swatch, note, items, gid):
|
||||
"""One group of download buttons. GPX comes first and is the primary button. Each
|
||||
link's accessible name starts with the group: "Main line: GPX, 1.1 MB"."""
|
||||
buttons = "".join(
|
||||
f'<a class="button{" button--primary" if d["format"] == "GPX" else ""}" '
|
||||
f'href="/trails/{esc(rec["id"])}/{esc(d["file"])}" download="{esc(d["file"])}">'
|
||||
f'{common.ICON_DOWNLOAD}<span class="vh">{esc(label)}: </span>{esc(d["format"])}<span class="vh">,</span> '
|
||||
f'<span class="button__meta">{esc(words.fmt_bytes(d["bytes"]))}</span></a>'
|
||||
for d in ordered_downloads(items))
|
||||
return f"""<li class="download">
|
||||
<p class="download__what">{swatch}<strong id="{gid}">{esc(label)}</strong><small>{esc(note)}</small></p>
|
||||
<div class="download__files">{buttons}</div>
|
||||
</li>"""
|
||||
|
||||
|
||||
def partial_notice(rec):
|
||||
"""The notice above the buttons when the line differs from the published length
|
||||
by more than 15%: the record's own numbers, then its length_gap_note."""
|
||||
if not common.line_differs(rec):
|
||||
return ""
|
||||
v = rec["verification"]
|
||||
diff = v["difference_percent"]
|
||||
head = "Partial line" if diff < 0 else "Longer than the published length"
|
||||
gap = rec["source"].get("length_gap_note", "")
|
||||
return f"""<div class="notice notice--partial">
|
||||
<h3>{head}</h3>
|
||||
<p>The line in the dataset measures {esc(words.fmt_km1(v["measured_km"]))} km against a published {esc(words.fmt_km(rec["length_km"]))} km ({esc(words.fmt_percent(diff))}).</p>
|
||||
{f"<p>{common.rich(gap)}</p>" if gap else ""}
|
||||
</div>"""
|
||||
|
||||
|
||||
def downloads_panel(rec):
|
||||
downloads = rec["derived"].get("downloads", [])
|
||||
if not downloads:
|
||||
return ""
|
||||
src = rec["source"]
|
||||
v = rec.get("verification", {})
|
||||
groups = []
|
||||
main = [d for d in downloads if d["role"] == "main"]
|
||||
if main:
|
||||
note = f"{src.get('line_source', '')}"
|
||||
if v.get("verified") and "measured_km" in v:
|
||||
parts = v.get("parts")
|
||||
note = (f"{words.fmt_km1(v['measured_km'])} km measured"
|
||||
+ (f" in {parts} part{'s' if parts != 1 else ''}" if parts else "") + f" · {note}")
|
||||
groups.append(download_group(rec, "Main line", common.SWATCH_ROUTE if common.is_route(rec) else common.SWATCH_LINE,
|
||||
note, main, "dl-main"))
|
||||
alts = [d for d in downloads if d["role"] == "alternates"]
|
||||
if alts:
|
||||
groups.append(download_group(rec, "Alternates and connectors", common.SWATCH_ALT,
|
||||
"Served separately by the source", alts, "dl-alt"))
|
||||
for i, d in enumerate(d for d in downloads if d["role"] == "extract"):
|
||||
key = d["file"][len(rec["id"]) + 1:-len(".geojson")]
|
||||
name = EXTRACT_SOURCES.get(key, key)
|
||||
# No swatch: extracts are not drawn on the map.
|
||||
groups.append(download_group(rec, f"Extract: {name}", "",
|
||||
"The line as this source serves it, before the sources were combined",
|
||||
[d], f"dl-x{i}"))
|
||||
licence = src.get("licence", "")
|
||||
licence_html = esc(words.label(words.LICENCES, licence))
|
||||
if licence in words.LICENCE_URLS:
|
||||
licence_html = ext_link(words.LICENCE_URLS[licence], words.label(words.LICENCES, licence))
|
||||
if "ODbL" in src.get("attribution", "") and licence != "ODbL-1.0":
|
||||
licence_html = Markup(f'{licence_html}; OpenStreetMap parts {ext_link(words.LICENCE_URLS["ODbL-1.0"], "ODbL 1.0")}')
|
||||
osm_note = ("<p class=\"note\">Lines from OpenStreetMap need the credit “© OpenStreetMap contributors” "
|
||||
"and stay under the ODbL (share-alike).</p>") if "ODbL" in src.get("attribution", "") + licence else ""
|
||||
release = (f'<p class="note"><a href="/trails/{esc(rec["id"])}/release.txt">release.txt</a>: '
|
||||
f"the source, licence and date the line files came from.</p>"
|
||||
if rec["derived"].get("release") else "")
|
||||
return f"""<section class="panel" id="download" aria-labelledby="download-title">
|
||||
<h2 class="panel__head" id="download-title">Download the line</h2>
|
||||
<div class="panel__body">
|
||||
{partial_notice(rec)}
|
||||
<p class="note">GPX is simplified to 5 m for devices. GeoJSON is the full-resolution line as published in this dataset. Neither carries elevation.</p>
|
||||
<ul class="downloads">{"".join(groups)}</ul>
|
||||
<div class="credit">
|
||||
<p class="credit__label" id="credit-label">Credit the source</p>
|
||||
<p class="credit__text" id="credit-text">{esc(common.credit_text(src.get("attribution", "")))}</p>
|
||||
<div class="credit__row">
|
||||
<span class="credit__licence">Licence: {licence_html}</span>
|
||||
<button class="button button--quiet" type="button" data-copy="#credit-text" data-copy-status="#credit-done" aria-describedby="credit-label" hidden>Copy credit</button>
|
||||
</div>
|
||||
<p class="credit__done" id="credit-done" role="status"></p>
|
||||
{osm_note}
|
||||
</div>
|
||||
{release}
|
||||
</div>
|
||||
</section>"""
|
||||
|
||||
|
||||
def guide_card(g, i):
|
||||
rows = [fact("Author", g.get("author", ""))]
|
||||
if g.get("publisher"):
|
||||
rows.append(fact("Publisher", g["publisher"]))
|
||||
if g.get("isbn"):
|
||||
rows.append(Markup(f'<div><dt>ISBN</dt><dd><span class="nowrap">{esc(g["isbn"])}</span></dd></div>'))
|
||||
rows.append(fact("Format", g.get("format", "")))
|
||||
if g.get("price"):
|
||||
rows.append(fact("Price", g["price"], f"As the page stated it on {g.get('price_checked', '')}"
|
||||
if g.get("price_checked") else ""))
|
||||
access = g.get("access", "")
|
||||
return f"""<li class="guide">
|
||||
<p class="guide__tags"><span class="access access--{esc(access)}">{esc(words.ACCESS.get(access, access))}</span></p>
|
||||
<h3 id="guide-{i}">{esc(g.get("title", ""))}</h3>
|
||||
{facts(*rows)}
|
||||
<a class="button button--link" href="{esc(g.get("url", ""))}" aria-describedby="guide-{i}">Guide page on {esc(host(g.get("url", "")))} {common.ICON_EXTERNAL}</a>
|
||||
</li>"""
|
||||
|
||||
|
||||
def guides_panel(rec):
|
||||
guides = rec.get("guide", [])
|
||||
if not guides:
|
||||
return ""
|
||||
cards = "".join(guide_card(g, i) for i, g in enumerate(guides, 1))
|
||||
return f"""<section class="panel" aria-labelledby="guides-title">
|
||||
<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’s or publisher’s own page for each guide.</p>
|
||||
</div>
|
||||
</section>"""
|
||||
|
||||
|
||||
def _is_url(value):
|
||||
return isinstance(value, str) and value.startswith(("http://", "https://"))
|
||||
|
||||
|
||||
def links_panel(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"]
|
||||
osm = rec.get("osm", {})
|
||||
sh = rec.get("shield", {})
|
||||
publisher = org_name(src.get("publisher", ""))
|
||||
items = {} # url -> [title, [what it is, ...]]; one entry per URL, titled by its first use
|
||||
|
||||
def add(url, title, what):
|
||||
if url in items:
|
||||
items[url][1].append(what)
|
||||
else:
|
||||
items[url] = [title, [what]]
|
||||
|
||||
kind = "route" if common.is_route(rec) else "trail"
|
||||
if src.get("publisher_url"):
|
||||
add(src["publisher_url"], publisher or host(src["publisher_url"]), f"The publisher's page for the {kind}")
|
||||
if osm.get("relation"):
|
||||
add(f"https://www.openstreetmap.org/relation/{osm['relation']}",
|
||||
f"OpenStreetMap relation {osm['relation']}", f"The {kind} as mapped in OpenStreetMap")
|
||||
if src.get("url"):
|
||||
what = "Where the included line came from" if common.has_line(rec) else "Where to ask for the line"
|
||||
title = "OpenStreetMap" if host(src["url"]).endswith("openstreetmap.org") else (publisher or host(src["url"]))
|
||||
add(src["url"], title, what)
|
||||
for g in rec.get("guide", []):
|
||||
if g.get("url") in items:
|
||||
add(g["url"], "", "A guide to the route")
|
||||
words_url = rec.get("route", {}).get("creator_words_url")
|
||||
if words_url:
|
||||
by = rec["route"].get("creator_words_by") or rec["route"].get("creator", "")
|
||||
add(words_url, by or host(words_url), "Where the quoted words were read")
|
||||
if _is_url(sh.get("logo_source")):
|
||||
owner = sh.get("logo_owner") or sh.get("contact") or host(sh["logo_source"])
|
||||
add(sh["logo_source"], owner, "The page the logo was taken from")
|
||||
add(f"/trails/{rec['id']}/trail.toml", "trail.toml", "The record itself, as data")
|
||||
if rec["derived"].get("release"):
|
||||
add(f"/trails/{rec['id']}/release.txt", "release.txt", "Source, licence and date of the line files")
|
||||
|
||||
def describe(url, whats):
|
||||
text = "; ".join([whats[0]] + [w[:1].lower() + w[1:] for w in whats[1:]])
|
||||
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>"""
|
||||
|
||||
|
||||
# Main column ----------------------------------------------------------------
|
||||
|
||||
def policy_scale(current):
|
||||
items = []
|
||||
for p in ("open", "sold", "withheld", "unclear"):
|
||||
lab, short, rule = words.POLICIES[p]
|
||||
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="Line policies for person-defined routes">{"".join(items)}</ol>')
|
||||
|
||||
|
||||
def route_block(rec):
|
||||
r = rec["route"]
|
||||
p = r.get("line_policy", "")
|
||||
rows = [
|
||||
fact("Creator", r.get("creator", "")),
|
||||
fact("First published", str(r["year"])) if r.get("year") else
|
||||
fact("First published", "Not recorded", "No page read states a year"),
|
||||
fact("Line policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p)),
|
||||
]
|
||||
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’s words</span>'
|
||||
if r.get("creator_words_by") else '<span class="tag tag--quiet">The creator’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>
|
||||
<figcaption>
|
||||
<p class="quote__who"><strong>{esc(by)}</strong> {not_creator}</p>
|
||||
{f'<p>Read on {ext_link(url)}.</p>' if url else ""}
|
||||
</figcaption>
|
||||
</figure>"""
|
||||
note = f'<h3 class="block__sub">About the route</h3>{record_text(r["note"])}' if r.get("note") else ""
|
||||
return block("route-title", "The route", facts(*rows) + Markup(quote) + policy_scale(p) + Markup(note))
|
||||
|
||||
|
||||
def listing_note(rec):
|
||||
"""The Listing row's note. A held record is listed but not settled; its wave_note
|
||||
(quoted, never paraphrased) says what. Other records show their wave_note as it is."""
|
||||
wave = str(rec.get("wave", ""))
|
||||
note = rec.get("wave_note", "")
|
||||
if wave != "held":
|
||||
return note or words.meaning(words.WAVES, wave)
|
||||
meaning = words.meaning(words.WAVES, wave)
|
||||
if note:
|
||||
return Markup(f"{esc(meaning)}. The record’s note: “{common.rich(note)}”")
|
||||
return f"{meaning}. The record has no note saying what."
|
||||
|
||||
|
||||
def record_block(rec):
|
||||
k = common.kind(rec)
|
||||
tier = rec.get("tier", "")
|
||||
wave = str(rec.get("wave", ""))
|
||||
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)}')
|
||||
rows = [
|
||||
fact("Kind", words.label(words.KINDS, k), words.meaning(words.KINDS, k)),
|
||||
fact("Designation", rec.get("designation", "")),
|
||||
fact("Tier", words.label(words.TIERS, tier), words.meaning(words.TIERS, tier)),
|
||||
fact("Listing", words.label(words.WAVES, wave), listing_note(rec)),
|
||||
]
|
||||
if rec.get("inclusion"):
|
||||
inc = rec["inclusion"]
|
||||
rows.append(fact("Inclusion", words.label(words.INCLUSION, inc), words.meaning(words.INCLUSION, inc)))
|
||||
rows += [
|
||||
Markup(f'<div><dt>Where</dt><dd>{where}</dd></div>'),
|
||||
Markup(f'<div><dt>Published length</dt><dd>{words.length(rec["length_km"], "inline", rec["derived"]["length_mi"])}'
|
||||
f'<small>{esc(rec.get("length_note", ""))}. A check value, not measured from the line.</small></dd></div>'),
|
||||
fact("Short name", rec.get("short_name", "")),
|
||||
fact("Record ID", Markup(code(rec["id"])), "Stable: the directory name, never changed"),
|
||||
]
|
||||
return block("record-title", "The record", facts(*rows))
|
||||
|
||||
|
||||
def gauge(diff):
|
||||
span = GAUGE_MAX - GAUGE_MIN
|
||||
pos = (min(max(diff, GAUGE_MIN), GAUGE_MAX) - GAUGE_MIN) / span * 100
|
||||
off = "low" if diff < GAUGE_MIN else "high" if diff > GAUGE_MAX else ""
|
||||
inside = abs(diff) <= GAUGE_LIMIT
|
||||
side = "shorter than" if diff < 0 else "longer than" if diff > 0 else "the same as"
|
||||
label = (f"Measured line is {abs(diff):.1f} percent {side} the published length, "
|
||||
f"{'inside' if inside else 'outside'} the 15 percent limit.")
|
||||
mark_text = words.fmt_percent(diff) + (" (off the scale)" if off else "")
|
||||
ticks = (GAUGE_MIN, -GAUGE_LIMIT, 0, GAUGE_LIMIT, GAUGE_MAX) # placed by .gauge__tick--N in style.css
|
||||
scale = "".join(f'<span class="gauge__tick--{i}">{esc(words.fmt_percent(v).replace(".0%", "%") if v else "0")}</span>'
|
||||
for i, v in enumerate(ticks))
|
||||
return Markup(f"""<figure class="gauge{f" gauge--off-{off}" if off else ""}">
|
||||
<div class="gauge__track" role="img" aria-label="{esc(label)}">
|
||||
<span class="gauge__band"></span>
|
||||
<span class="gauge__zero"></span>
|
||||
<span class="gauge__mark" style="--pos: {pos:.2f}%" data-label="{esc(mark_text)}"></span>
|
||||
</div>
|
||||
<div class="gauge__scale" aria-hidden="true">{scale}</div>
|
||||
<figcaption class="gauge__legend">
|
||||
<span><span class="gauge__key" aria-hidden="true"></span>Within 15% of the published length</span>
|
||||
<span><span class="gauge__key gauge__key--out" aria-hidden="true"></span>Beyond 15%: the record must say why</span>
|
||||
</figcaption>
|
||||
</figure>""")
|
||||
|
||||
|
||||
def verification_block(rec):
|
||||
v = rec.get("verification", {})
|
||||
src = rec["source"]
|
||||
gap = src.get("length_gap_note", "")
|
||||
if gap and common.line_differs(rec) and rec["derived"].get("downloads"):
|
||||
# The download panel's notice carries the note, beside the files it is about.
|
||||
gap_html = '<p class="note">Why the lengths differ: see the notice in <a href="#download">Download the line</a>.</p>'
|
||||
elif gap:
|
||||
gap_html = f'<div class="notice"><h3>Why the lengths differ</h3><p>{common.rich(gap)}</p></div>'
|
||||
else:
|
||||
gap_html = ""
|
||||
if v.get("verified") and "measured_km" in v:
|
||||
diff = v.get("difference_percent", 0)
|
||||
parts = v.get("parts")
|
||||
compare = f"""<dl class="compare">
|
||||
<div><dt>Published</dt><dd>{words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}</dd></div>
|
||||
<div><dt>Measured</dt><dd>{words.length(v["measured_km"], "stack", measured=True)}<small>geodesic, from the line</small></dd></div>
|
||||
<div><dt>Difference</dt><dd>{esc(words.fmt_percent(diff))}<small>measured minus published</small></dd></div>
|
||||
<div><dt>Parts</dt><dd>{esc(parts if parts is not None else "Not recorded")}<small>pieces left after joining ends within 100 m</small></dd></div>
|
||||
</dl>"""
|
||||
content = Markup(compare) + gauge(diff) + record_text(v.get("note", "")) + Markup(gap_html)
|
||||
extra = Markup(f' <span class="tag">Checked {esc(v.get("date", ""))}</span>') if v.get("date") else ""
|
||||
verified_row = facts(fact("Measured", "Yes", "The line was downloaded and measured"))
|
||||
return block("verify-title", "Verification", verified_row + content, extra)
|
||||
if not common.has_line(rec) and restates_no_line(v.get("note", "")) and not gap:
|
||||
return "" # "No line to measure": the record only restates that there is no line
|
||||
rows = facts(fact("Measured", "No", "No line was downloaded and measured"))
|
||||
return block("verify-title", "Verification", rows + record_text(v.get("note", "")) + Markup(gap_html))
|
||||
|
||||
|
||||
def source_block(rec):
|
||||
src = rec["source"]
|
||||
line = common.has_line(rec)
|
||||
status = src.get("status", "")
|
||||
licence = src.get("licence", "")
|
||||
licence_value = words.label(words.LICENCES, licence)
|
||||
licence_html = (ext_link(words.LICENCE_URLS[licence], licence_value) if licence in words.LICENCE_URLS
|
||||
else esc(licence_value))
|
||||
source_help = '<small>Where to ask for the line: a layer or relation page</small>' if line else ""
|
||||
|
||||
def keep(value):
|
||||
"""Rows of a record with no line are left out when they only restate that."""
|
||||
return line or not restates_no_line(value)
|
||||
|
||||
rows = [
|
||||
fact("Line in this dataset", src.get("line_file"), "The main line file of the record") if line else "",
|
||||
fact("Source status", words.label(words.SOURCE_STATUS, status), words.meaning(words.SOURCE_STATUS, status)),
|
||||
fact("Publisher", src.get("publisher", "")),
|
||||
Markup(f'<div><dt>Publisher’s page</dt><dd>{ext_link(src["publisher_url"])}</dd></div>') if src.get("publisher_url") else "",
|
||||
Markup(f'<div><dt>Source</dt><dd>{ext_link(src["url"])}{source_help}</dd></div>') if src.get("url") else "",
|
||||
fact("Line source", src.get("line_source", "")) if keep(src.get("line_source")) else "",
|
||||
fact("Format", src.get("format", "")) if keep(src.get("format")) else "",
|
||||
fact("Main line", src.get("mainline", ""), "How the main line is told apart from alternates, connectors and side trails"),
|
||||
fact("Coordinates", src.get("crs", ""), "What the source stores; published files are longitude/latitude (EPSG:4326)") if line else "",
|
||||
Markup(f'<div><dt>Licence</dt><dd>{licence_html}</dd></div>'),
|
||||
fact("Credit", common.credit_text(src.get("attribution", "")), "The credit line to show, as the source asks")
|
||||
if keep(src.get("attribution")) else "",
|
||||
fact("May be passed on", yes_no(src.get("redistributable")),
|
||||
"The source's terms allow its line to be passed on" if src.get("redistributable") else
|
||||
"The source's terms do not allow its line to be passed on") if line else "",
|
||||
fact("OpenStreetMap only", yes_no(src.get("osm_only")),
|
||||
"OpenStreetMap is the only source of the included line" if src.get("osm_only") else "") if line else "",
|
||||
fact("Source checked", src.get("source_checked", "")),
|
||||
fact("Newer release?", src["discovery"], "How to tell whether the source has a newer release") if src.get("discovery") else "",
|
||||
]
|
||||
if src.get("decision") or src.get("decision_text"):
|
||||
rows.append(fact("Decision", src.get("decision_text", "") or words.DECISIONS.get(src.get("decision", ""), src.get("decision", ""))))
|
||||
licence_text = (f'<h3 class="block__sub">What the source says</h3>{record_text(src["licence_text"])}'
|
||||
'<p class="note">With the page it was read on. Not legal advice.</p>') if src.get("licence_text") else ""
|
||||
return block("source-title", "Source and licence", facts(*rows) + Markup(licence_text))
|
||||
|
||||
|
||||
def osm_block(rec):
|
||||
osm = rec.get("osm", {})
|
||||
rel = osm.get("relation", 0)
|
||||
if rel:
|
||||
value = Markup(f'<div><dt>Relation</dt><dd>{ext_link(f"https://www.openstreetmap.org/relation/{rel}", str(rel))}</dd></div>')
|
||||
elif common.has_line(rec):
|
||||
value = fact("Relation", "None recorded", "No relation found, or not searched")
|
||||
else:
|
||||
value = "" # no line and no relation: nothing to say beyond the note
|
||||
return block("osm-title", "OpenStreetMap", facts(value, fact("Note", osm.get("note", ""))))
|
||||
|
||||
|
||||
def logo_block(rec):
|
||||
sh = rec.get("shield", {})
|
||||
status = sh.get("status", "")
|
||||
if not common.shield_url(rec):
|
||||
# No logo file: one line, the status and the record's note.
|
||||
lead = {"no-logo-exists": "No logo", "logo-not-found": "Logo not found",
|
||||
"use-real-logo": "Logo not included"}.get(status, "No logo file")
|
||||
note = sh.get("note", "")
|
||||
return block("logo-title", "Logo", Markup(
|
||||
f'<p class="record-text"><strong>{esc(lead)}.</strong>{" " + common.rich(note) if note else ""}</p>'))
|
||||
rows = [
|
||||
fact("Status", words.label(words.SHIELD_STATUS, status), words.meaning(words.SHIELD_STATUS, status)),
|
||||
fact("Holder", sh.get("logo_owner", "")) if sh.get("logo_owner") else "",
|
||||
fact("Contact", sh.get("contact", "")) if sh.get("contact") and sh.get("contact") != sh.get("logo_owner") else "",
|
||||
Markup(f'<div><dt>Taken from</dt><dd>{ext_link(sh["logo_source"])}</dd></div>') if _is_url(sh.get("logo_source"))
|
||||
else fact("Taken from", sh.get("logo_source") or "Not recorded"),
|
||||
fact("File", sh.get("logo_file", "")),
|
||||
fact("Note", sh.get("note", "")),
|
||||
]
|
||||
federal = ("<p>Some logos are official emblems of United States National Scenic or Historic Trails. "
|
||||
"Those emblems are federal insignia; their use here is for identification only.</p>"
|
||||
if rec.get("tier") == "national" or "National Historic Trail" in rec.get("designation", "") else "")
|
||||
notice = f"""<div class="notice">
|
||||
<h3>Shown only to identify the trail</h3>
|
||||
<p>This logo belongs to {esc(sh.get("logo_owner", "its holder"))}. It is not covered by this dataset’s licences, and no right to use it for any other purpose is given or implied.</p>
|
||||
{federal}
|
||||
<p>A holder who wants a logo removed, replaced or credited differently can ask; see <a href="/logos/">Logos</a>.</p>
|
||||
</div>"""
|
||||
return block("logo-title", "Logo", Markup(notice) + facts(*rows))
|
||||
|
||||
|
||||
def correction_block(rec, site):
|
||||
parts = []
|
||||
if common.is_route(rec):
|
||||
parts.append(f"""<div class="notice">
|
||||
<h3>If you made this route</h3>
|
||||
<p>A route’s creator can ask for its record to be corrected or removed, and the record will be corrected or removed. Say which route: {code(rec["id"])}. See <a href="/about/">About</a>.</p>
|
||||
</div>""")
|
||||
if site.issues_url:
|
||||
parts.append(f"""<p class="prose">Found an error? <a href="{esc(site.issues_url)}">Open an issue</a> with the record ID ({code(rec["id"])}), what is wrong, and where the correct information can be checked: a source page, a map, or a measured line.</p>""")
|
||||
if not parts:
|
||||
return ""
|
||||
return block("correct-title", "Corrections", Markup("".join(parts)))
|
||||
|
||||
|
||||
def flatten(obj, prefix=""):
|
||||
"""(field, value) for every leaf of a record: "source.licence", "guide[0].title", "regions[1]"."""
|
||||
if isinstance(obj, dict):
|
||||
for k, v in obj.items():
|
||||
yield from flatten(v, f"{prefix}.{k}" if prefix else k)
|
||||
elif isinstance(obj, list):
|
||||
for i, v in enumerate(obj):
|
||||
yield from flatten(v, f"{prefix}[{i}]")
|
||||
else:
|
||||
yield prefix, obj
|
||||
|
||||
|
||||
def raw_value(value):
|
||||
"""A value as the record stores it: true/false, numbers as written, "" for an empty string."""
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
if isinstance(value, str):
|
||||
return value if value else '""'
|
||||
return str(value)
|
||||
|
||||
|
||||
def raw_record(rec):
|
||||
"""Every field of the record with its exact value, as the last block of the page."""
|
||||
fields = {k: v for k, v in rec.items() if k != "derived"}
|
||||
rows = "".join(f'<tr><th scope="row"><code>{esc(field)}</code></th><td>{esc(raw_value(value))}</td></tr>'
|
||||
for field, value in flatten(fields))
|
||||
return Markup(f"""<details class="rawrecord">
|
||||
<summary>Every field of the record, with its exact value</summary>
|
||||
<p class="note">As stored in <a href="/trails/{esc(rec["id"])}/trail.toml">trail.toml</a>.
|
||||
The <a href="/data/schema/">record schema</a> says what each field means.</p>
|
||||
<div class="table-wrap"><table class="rawrecord__table">
|
||||
<thead><tr><th scope="col">Field</th><th scope="col">Value</th></tr></thead>
|
||||
<tbody>{rows}</tbody>
|
||||
</table></div>
|
||||
</details>""")
|
||||
|
||||
|
||||
# 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 line as GeoJSON or GPX, with the source, licence and credit."
|
||||
else:
|
||||
text += "Record only: " + common.absent_reason_short(rec)
|
||||
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."""
|
||||
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)
|
||||
body = f"""{page_head(rec)}
|
||||
<div class="container detail">
|
||||
{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>
|
||||
</div>"""
|
||||
return rec["name"], description(rec), body, has_map
|
||||
|
||||
|
||||
def release_path(repo_root, rec):
|
||||
path = os.path.join(repo_root, rec["id"], "release.txt")
|
||||
return path if os.path.isfile(path) else ""
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Plain words for the record's coded values, and number formatting.
|
||||
|
||||
Every coded value in docs/schema.md that a page shows has a label here, with
|
||||
a one-line meaning taken from the schema or the README.
|
||||
"""
|
||||
from .markup import Markup, esc
|
||||
|
||||
KM_PER_MI = 1.609344
|
||||
|
||||
COUNTRIES = {"US": "United States", "CA": "Canada"}
|
||||
|
||||
US_STATES = {
|
||||
"AK": "Alaska", "AL": "Alabama", "AR": "Arkansas", "AZ": "Arizona", "CA": "California",
|
||||
"CO": "Colorado", "CT": "Connecticut", "DC": "District of Columbia", "DE": "Delaware",
|
||||
"FL": "Florida", "GA": "Georgia", "HI": "Hawaii", "IA": "Iowa", "ID": "Idaho", "IL": "Illinois",
|
||||
"IN": "Indiana", "KS": "Kansas", "KY": "Kentucky", "LA": "Louisiana", "MA": "Massachusetts",
|
||||
"MD": "Maryland", "ME": "Maine", "MI": "Michigan", "MN": "Minnesota", "MO": "Missouri",
|
||||
"MS": "Mississippi", "MT": "Montana", "NC": "North Carolina", "ND": "North Dakota",
|
||||
"NE": "Nebraska", "NH": "New Hampshire", "NJ": "New Jersey", "NM": "New Mexico", "NV": "Nevada",
|
||||
"NY": "New York", "OH": "Ohio", "OK": "Oklahoma", "OR": "Oregon", "PA": "Pennsylvania",
|
||||
"RI": "Rhode Island", "SC": "South Carolina", "SD": "South Dakota", "TN": "Tennessee",
|
||||
"TX": "Texas", "UT": "Utah", "VA": "Virginia", "VT": "Vermont", "WA": "Washington",
|
||||
"WI": "Wisconsin", "WV": "West Virginia", "WY": "Wyoming",
|
||||
}
|
||||
CA_PROVINCES = {
|
||||
"AB": "Alberta", "BC": "British Columbia", "MB": "Manitoba", "NB": "New Brunswick",
|
||||
"NL": "Newfoundland and Labrador", "NS": "Nova Scotia", "NT": "Northwest Territories",
|
||||
"NU": "Nunavut", "ON": "Ontario", "PE": "Prince Edward Island", "QC": "Quebec",
|
||||
"SK": "Saskatchewan", "YT": "Yukon",
|
||||
}
|
||||
ALL_CANADA = "all provinces and territories"
|
||||
|
||||
# (label, meaning). Meanings follow docs/schema.md and README.md.
|
||||
TIERS = {
|
||||
"national": ("National Scenic Trail", "A United States National Scenic Trail"),
|
||||
"regional": ("Regional", "A long trail of 80 km (50 mi) or more"),
|
||||
"short": ("Short", "A well-known multi-day trail of 60 to 80 km"),
|
||||
"deferred": ("Deferred", "Listed, but something about it is not settled; the record's note says what"),
|
||||
"candidate": ("Candidate", "Listing not yet decided"),
|
||||
}
|
||||
WAVES = {
|
||||
"1": ("First set", "In the first set of trails"),
|
||||
"held": ("Held", "Listed, but something about it is not settled"),
|
||||
}
|
||||
INCLUSION = {
|
||||
"nst-unconditional": ("Listed unconditionally", "Every National Scenic Trail is listed"),
|
||||
"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"),
|
||||
}
|
||||
SOURCE_STATUS = {
|
||||
"verified": ("Verified", "The line was downloaded from the source and measured"),
|
||||
"found": ("Found", "The source was located but not downloaded"),
|
||||
"osm-only": ("OpenStreetMap only", "The only source is an OpenStreetMap route relation"),
|
||||
"none": ("None", "No source of a line"),
|
||||
}
|
||||
LICENCES = {
|
||||
"us-gov-public-domain": "US public domain",
|
||||
"CC-BY-4.0": "CC BY 4.0",
|
||||
"CC-BY": "CC BY",
|
||||
"ODbL-1.0": "ODbL 1.0",
|
||||
"CC-BY-NC-ND-4.0": "CC BY-NC-ND 4.0",
|
||||
"none-stated": "None stated",
|
||||
"restricted": "Restricted",
|
||||
"unknown": "Unknown",
|
||||
}
|
||||
LICENCE_URLS = {
|
||||
"us-gov-public-domain": "https://www.usa.gov/government-works",
|
||||
"CC-BY-4.0": "https://creativecommons.org/licenses/by/4.0/",
|
||||
"ODbL-1.0": "https://opendatacommons.org/licenses/odbl/1-0/",
|
||||
"CC-BY-NC-ND-4.0": "https://creativecommons.org/licenses/by-nc-nd/4.0/",
|
||||
}
|
||||
POLICIES = {
|
||||
"open": ("Open", "The creator publishes the line freely",
|
||||
"A line 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."),
|
||||
"sold": ("Sold", "The route is got by buying a guide or map set",
|
||||
"No line is included from any source, OpenStreetMap included."),
|
||||
"withheld": ("Withheld", "The creator chooses not to publish a line",
|
||||
"No line is included from any source, OpenStreetMap included."),
|
||||
"unclear": ("Unclear", "Whether the creator shares the line is not settled",
|
||||
"No line is included until it is settled."),
|
||||
}
|
||||
SHIELD_STATUS = {
|
||||
"use-real-logo": ("Logo in use", "The trail has a logo"),
|
||||
"no-logo-exists": ("No logo", "No logo exists for this trail"),
|
||||
"logo-not-found": ("Logo not found", "No logo file was found"),
|
||||
}
|
||||
ACCESS = {"free": "Free", "purchase": "Purchase"}
|
||||
DECISIONS = {"included-named": "Included with its name"}
|
||||
|
||||
|
||||
def label(table, key):
|
||||
"""The label for a coded value; the raw value itself when the table has none."""
|
||||
entry = table.get(str(key))
|
||||
return entry[0] if isinstance(entry, tuple) else (entry or str(key))
|
||||
|
||||
|
||||
def meaning(table, key):
|
||||
entry = table.get(str(key))
|
||||
return entry[1] if isinstance(entry, tuple) else ""
|
||||
|
||||
|
||||
def region_name(code):
|
||||
if code == ALL_CANADA:
|
||||
return "All provinces and territories"
|
||||
return US_STATES.get(code) or CA_PROVINCES.get(code) or code
|
||||
|
||||
|
||||
def region_country(code):
|
||||
""""US" or "CA" for a state, province or territory code; "CA" for all of Canada; "" when unknown."""
|
||||
if code == ALL_CANADA or code in CA_PROVINCES:
|
||||
return "CA"
|
||||
if code in US_STATES:
|
||||
return "US"
|
||||
return ""
|
||||
|
||||
|
||||
def region_key(code, country):
|
||||
"""Filter value for a region: "US-AZ", "CA-ON"; "CA-*" for all of Canada."""
|
||||
if code == ALL_CANADA:
|
||||
return "CA-*"
|
||||
if code in CA_PROVINCES:
|
||||
return f"CA-{code}"
|
||||
if code in US_STATES:
|
||||
return f"US-{code}"
|
||||
return f"{country}-{code}"
|
||||
|
||||
|
||||
def fmt_int(n):
|
||||
return f"{int(round(n)):,}"
|
||||
|
||||
|
||||
def fmt_km(km):
|
||||
"""1287 -> "1,287"; 1255.1 -> "1,255.1"."""
|
||||
if float(km).is_integer():
|
||||
return f"{int(km):,}"
|
||||
return f"{km:,.1f}"
|
||||
|
||||
|
||||
def fmt_km1(km):
|
||||
"""A measured length, always with one decimal: 2.0 -> "2.0", 1141 -> "1,141.0"."""
|
||||
return f"{float(km):,.1f}"
|
||||
|
||||
|
||||
def km_to_mi(km):
|
||||
return km / KM_PER_MI
|
||||
|
||||
|
||||
def fmt_percent(p):
|
||||
"""-2.5 -> "−2.5%" (true minus sign), 0.9 -> "+0.9%", 0 -> "0.0%"."""
|
||||
if p == 0:
|
||||
return "0.0%"
|
||||
sign = "+" if p > 0 else "−"
|
||||
return f"{sign}{abs(p):.1f}%"
|
||||
|
||||
|
||||
def fmt_bytes(n):
|
||||
if n >= 1_000_000:
|
||||
return f"{n / 1_000_000:.1f} MB"
|
||||
if n >= 1_000:
|
||||
return f"{round(n / 1_000):,} KB"
|
||||
return f"{n} B"
|
||||
|
||||
|
||||
def length(km, style="inline", mi=None, measured=False):
|
||||
"""A length in both units. The reader's unit preference decides the order (CSS).
|
||||
|
||||
style "inline": "1,287 km (800 mi)"; "stack": large first unit over small second.
|
||||
measured: a measured length, always written with its one decimal ("2.0 km").
|
||||
"""
|
||||
mi = km_to_mi(km) if mi is None else mi
|
||||
km_text = f"{fmt_km1(km) if measured else fmt_km(km)} km"
|
||||
whole = float(km).is_integer() and not measured
|
||||
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>')
|
||||
Reference in new issue
Block a user