Add 130 views of the same records, speed up map pages, and say who maintains the site
- New pages built from the records: lists by length, time to walk, month, kind of walking and holder; place-by-list pages; a Triple Crown table and key-figure tables for the National Scenic and Recreation Trails; highest points, most climbing and climb per mile; a page for every route author, with the authors of three or more routes leading the authors page; connected trails; recently added and changed; a glossary and a method page. Every place page opens with a summary. - Trail pages open with an "In brief" paragraph generated from the record and show when the record was last checked. The About page says who maintains the site and how to reach them. - The map starts when it is reached, not with the page. The site's own CSS, scripts and fonts are fingerprinted and cached for a year. Every image has its dimensions. - Titles are held to 60 characters and share previews get their own shorter description. - Social cards are redrawn so a long name can no longer push text into the footer, and the site-wide card takes its wording from the site settings instead of an old hand-made image. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
5b80fccd1e
commit
f2d3b71810
266 files changed
+4658
-252
No files matched your search
@@ -0,0 +1,258 @@
|
||||
"""Route authors: /authors/ and a page for every author who has at least one route.
|
||||
|
||||
A route's author is the free text of its [route].creator. authors.toml names a person (or an
|
||||
organisation) with each exact credit that names them, so one page can list every route credited
|
||||
to them, in any form. A credit that names two or more people appears under each of them, so the
|
||||
route is on each page, and each page says who else is credited. A credit that authors.toml does
|
||||
not list stands alone as its own author, and is not typed as a person. Where a route is
|
||||
published comes from its [[guide]] entries.
|
||||
|
||||
PROMINENT_MIN is the number of routes at which an author is shown at the top of /authors/,
|
||||
in a block of their own, instead of in the alphabetical list below it. Change it here and the
|
||||
page follows: an author who reaches it moves up with no other change.
|
||||
"""
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
from . import common, datafiles, facets, hike, home, pagekit, regions, seo, summary, trail, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
INDEX = "/authors/"
|
||||
PROMINENT_MIN = 3
|
||||
NOT_NAMED = "Author not named"
|
||||
TITLE_LIMIT = 60 # the page's own title, before the site name
|
||||
|
||||
|
||||
def slug(name):
|
||||
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
|
||||
|
||||
|
||||
def groups(records, repo_root):
|
||||
"""[{name, slug, kind, credits, routes, others}] for every route author, sorted by name.
|
||||
kind: "person" or "organisation" as authors.toml says, "" for a credit it does not list.
|
||||
others: {route id: [the other authors the route's credit names]}."""
|
||||
entries = {a["name"]: a for a in datafiles.authors(repo_root)}
|
||||
named = {} # credit -> [author names in authors.toml order]
|
||||
for a in datafiles.authors(repo_root):
|
||||
for c in a.get("credits", []):
|
||||
named.setdefault(c, []).append(a["name"])
|
||||
by_name = {}
|
||||
for r in (r for r in records if facets.kind(r) == "route"):
|
||||
credit = facets.author(r) or NOT_NAMED
|
||||
names = named.get(credit) or [credit]
|
||||
for name in names:
|
||||
g = by_name.setdefault(name, {"name": name, "slug": slug(name), "kind": entries.get(name, {}).get("kind", "person") if name in entries else "",
|
||||
"credits": set(), "routes": [], "others": {}})
|
||||
g["credits"].add(credit)
|
||||
g["routes"].append(r)
|
||||
g["others"][r["id"]] = [n for n in names if n != name]
|
||||
out = sorted(by_name.values(), key=lambda g: g["name"].lower())
|
||||
for g in out:
|
||||
g["routes"].sort(key=home.sort_name)
|
||||
return out
|
||||
|
||||
|
||||
def author_pages(records, repo_root):
|
||||
"""Every author with a route has a page; a route with no author named has none to give."""
|
||||
return [g for g in groups(records, repo_root) if g["name"] != NOT_NAMED]
|
||||
|
||||
|
||||
def prominent(gs):
|
||||
"""The authors at or above PROMINENT_MIN routes, most routes first, then by name."""
|
||||
return sorted((g for g in gs if len(g["routes"]) >= PROMINENT_MIN), key=lambda g: (-len(g["routes"]), g["name"].lower()))
|
||||
|
||||
|
||||
def path(g):
|
||||
return f"{INDEX}{g['slug']}/"
|
||||
|
||||
|
||||
def link_map(records, repo_root):
|
||||
"""{credit: [(author name, page path)]} for each credit on a route, for the credit's own words on a route page."""
|
||||
out = {}
|
||||
for g in author_pages(records, repo_root):
|
||||
for c in g["credits"]:
|
||||
out.setdefault(c, []).append((g["name"], path(g)))
|
||||
return out
|
||||
|
||||
|
||||
def credit_html(credit, links):
|
||||
"""The credit as the record writes it, with each author's name in it a link to their page."""
|
||||
text = esc(credit)
|
||||
for name, href in links or []:
|
||||
n = esc(name)
|
||||
if n in text:
|
||||
text = text.replace(n, f'<a href="{esc(href)}">{n}</a>', 1)
|
||||
return Markup(text)
|
||||
|
||||
|
||||
def guide_text(rec):
|
||||
"""Where a route is published: its guides, each as a link with its format and whether it is free."""
|
||||
items = []
|
||||
for g in rec.get("guide", []):
|
||||
fmt = f", {esc(g['format'])}" if g.get("format") else ""
|
||||
access = words.ACCESS.get(g.get("access", ""), "").lower()
|
||||
items.append(f'<a href="{esc(g.get("url", ""))}">{esc(g.get("title", ""))}</a> ({access}{fmt})'.replace("( ", "("))
|
||||
return Markup("; ".join(items)) if items else "Not published as a guide"
|
||||
|
||||
|
||||
def year_text(rec):
|
||||
y = rec.get("route", {}).get("year")
|
||||
return str(y) if y else "Not on file"
|
||||
|
||||
|
||||
def _miles(rec):
|
||||
return f'{words.fmt_int(rec["derived"]["length_mi"])} miles ({words.fmt_km(rec["length_km"])} km)'
|
||||
|
||||
|
||||
def _plural(n, word):
|
||||
return f"{n} {word}{'' if n == 1 else 's'}"
|
||||
|
||||
|
||||
def own_sites(g):
|
||||
"""[(host, url)] where the records give the author's own page: a guide they wrote and publish
|
||||
themselves (no other publisher), or the page their own words were read on."""
|
||||
found = {}
|
||||
for r in g["routes"]:
|
||||
for gd in r.get("guide", []):
|
||||
if gd.get("url") and not gd.get("publisher") and any(c.lower() in gd.get("author", "").lower() for c in (g["name"],)):
|
||||
found.setdefault(urllib.parse.urlparse(gd["url"]).hostname or gd["url"], gd["url"])
|
||||
route = r.get("route", {})
|
||||
if route.get("creator_words_url") and not route.get("creator_words_by") and g["name"] in route.get("creator", "") \
|
||||
and not g["others"].get(r["id"]):
|
||||
found.setdefault(urllib.parse.urlparse(route["creator_words_url"]).hostname or "", route["creator_words_url"])
|
||||
return sorted(found.items())
|
||||
|
||||
|
||||
def _route_line(rec):
|
||||
return f'<a href="{esc(common.trail_path(rec))}">{esc(common.plain_name(rec))}</a> ({esc(words.fmt_int(rec["derived"]["length_mi"]))} miles)'
|
||||
|
||||
|
||||
def _route_links(g):
|
||||
return ", ".join(_route_line(r) for r in g["routes"])
|
||||
|
||||
|
||||
def _block(g):
|
||||
"""A prominent author as a card, in the style of the lists index: name, route count, each
|
||||
route with its length (which follows the units switch), and a link to their page."""
|
||||
n = len(g["routes"])
|
||||
items = "".join(f'<li><a href="{esc(common.trail_path(r))}">{esc(common.plain_name(r))}</a>'
|
||||
f'<span class="shelf__len">{words.length(r["length_km"], mi=r["derived"]["length_mi"])}</span></li>'
|
||||
for r in g["routes"])
|
||||
return (f'<li class="shelf shelf--author">\n'
|
||||
f' <h3 class="shelf__title"><a href="{esc(path(g))}">{esc(g["name"])}</a>'
|
||||
f' <span class="shelf__count" title="Routes on this site">{n}</span></h3>\n'
|
||||
f' <ul class="shelf__items">{items}</ul>\n'
|
||||
f' <p class="shelf__more"><a href="{esc(path(g))}">All {n} routes by {esc(g["name"])}</a></p>\n</li>')
|
||||
|
||||
|
||||
def index_page(records, site, repo_root):
|
||||
"""(title, description, body, routes) for /authors/."""
|
||||
gs = author_pages(records, repo_root)
|
||||
routes = [r for r in records if facets.kind(r) == "route"]
|
||||
top = prominent(gs)
|
||||
rest = [g for g in gs if g not in top]
|
||||
n_gpx = sum(1 for r in routes if facets.gpx_here(r))
|
||||
lede = (f"{len(routes)} long hiking routes, worked out by {len(gs)} authors. "
|
||||
f"Every author has a page of their own, with their routes and where each is published. "
|
||||
f"{n_gpx} of the routes {'has' if n_gpx == 1 else 'have'} a GPX here. {esc(facets.ROUTE_DEFINITION)}")
|
||||
sections = ""
|
||||
if top:
|
||||
blocks = "\n".join(_block(g) for g in top)
|
||||
sections += (f'<h2 id="most-routes">Authors with {PROMINENT_MIN} or more routes</h2>\n'
|
||||
f'<p class="note">{_plural(len(top), "author")}, the most routes first.</p>\n'
|
||||
f'<ul class="shelves shelves--wide">\n{blocks}\n</ul>\n')
|
||||
if rest:
|
||||
items = "\n".join(f'<li><a href="{esc(path(g))}">{esc(g["name"])}</a>, {_route_links(g)}</li>' for g in rest)
|
||||
heading = "Other authors" if top else "All authors"
|
||||
sections += f'<h2 id="other-authors">{heading}</h2>\n<ul class="author-list">\n{items}\n</ul>\n'
|
||||
rows = []
|
||||
for g in gs:
|
||||
first = True
|
||||
for r in g["routes"]:
|
||||
rows.append([Markup(f'<a href="{esc(path(g))}">{esc(g["name"])}</a>') if first else "", pagekit.trail_link(r), year_text(r),
|
||||
words.length(r["length_km"], mi=r["derived"]["length_mi"]), facets.GPX_STATUS[facets.gpx(r)], guide_text(r)])
|
||||
first = False
|
||||
body = (pagekit.head("Route authors", lede, [("Trails", "/"), ("Lists", "/lists/"), ("Routes", "/routes/")])
|
||||
+ f"""<div class="container section place">
|
||||
{sections}
|
||||
<h2 id="every-route">Every route, with its author</h2>
|
||||
{pagekit.table(["Author", "Route", "Year", "Length", "GPX", "Published in"], rows, caption="Routes by author")}
|
||||
<p class="finder__foot">A route credited to several people is listed under each of them. An author credited in more than one form is
|
||||
listed once, under the name authors.toml gives. Guides marked free are free; the rest are bought from the author or publisher.</p>
|
||||
<nav class="region-nav" aria-label="Related pages"><a href="/routes/">Routes with their guides</a> ·
|
||||
<a href="/glossary/#route">What a route is</a> · <a href="/lists/">All lists</a></nav>
|
||||
</div>""")
|
||||
title = "Long Hiking Route Authors: Who Published Which Route"
|
||||
desc = common.cut_at_word(f"{len(routes)} long hiking routes by {len(gs)} authors. Who has published the most routes, "
|
||||
"with each route's length and where it is published.", common.DESCRIPTION_LIMIT)
|
||||
return title, desc, Markup(body), routes
|
||||
|
||||
|
||||
def author_page(g, records, site, all_pages):
|
||||
"""(title, description, body, needs_map, routes, jsonld) for /authors/<slug>/."""
|
||||
routes = g["routes"]
|
||||
n = len(routes)
|
||||
credits = sorted(g["credits"], key=str.lower)
|
||||
lengths = [r["derived"]["length_mi"] for r in routes]
|
||||
if n == 1:
|
||||
lede = f"{esc(g['name'])} is credited with {esc(common.plain_name(routes[0]))}, {esc(_miles(routes[0]))}."
|
||||
else:
|
||||
lede = (f"{esc(g['name'])} is credited with {n} routes on this site, from {esc(words.fmt_int(min(lengths)))} "
|
||||
f"to {esc(words.fmt_int(max(lengths)))} miles.")
|
||||
forms = [c for c in credits if c != g["name"]]
|
||||
if forms:
|
||||
lede += " The records credit them as " + words.join_names(f"“{esc(c)}”" for c in forms) + "."
|
||||
sites = own_sites(g)
|
||||
if sites:
|
||||
lede += " Their own page: " + "; ".join(f'<a href="{esc(u)}">{esc(h)}</a>' for h, u in sites) + "."
|
||||
show_credit = any(r["route"].get("creator") != g["name"] for r in routes)
|
||||
rows = []
|
||||
for r in routes:
|
||||
cells = [pagekit.trail_link(r), words.length(r["length_km"], mi=r["derived"]["length_mi"]),
|
||||
trail.place_text(r).removeprefix("in "), hike.days(r) or "Not on file", guide_text(r)]
|
||||
if show_credit:
|
||||
credit = r["route"].get("creator", "")
|
||||
cells.append(esc(credit) if credit != g["name"] else "")
|
||||
rows.append(cells)
|
||||
heads = ["Route", "Length", "Where it runs", "Usual time", "Published in"] + (["Credited as"] if show_credit else [])
|
||||
shared = [r for r in routes if g["others"].get(r["id"])]
|
||||
shared_note = ""
|
||||
if shared:
|
||||
by_name = {x["name"]: x for x in all_pages}
|
||||
lines = []
|
||||
for r in shared:
|
||||
people = [f'<a href="{esc(path(by_name[o]))}">{esc(o)}</a>' if o in by_name else esc(o) for o in g["others"][r["id"]]]
|
||||
lines.append(f'{esc(common.plain_name(r))}: also credited to {words.join_names(people)}.')
|
||||
shared_note = '<p class="note">' + " ".join(lines) + "</p>"
|
||||
briefs = "".join(f'<h3><a href="{esc(common.trail_path(r))}">{esc(common.plain_name(r))}</a></h3>\n{trail.brief(r)}\n' for r in routes)
|
||||
nav_items = [x for x in prominent(all_pages) if x is not g]
|
||||
nav = (f'<nav class="region-nav" aria-label="Authors with the most routes">Authors with the most routes: '
|
||||
+ " · ".join(f'<a href="{esc(path(x))}">{esc(x["name"])}</a> ({len(x["routes"])})' for x in nav_items) + "</nav>") if nav_items else ""
|
||||
more = (f'<div class="prose place-summary">{summary.facts(routes, records)}</div>' if n >= 3 else "")
|
||||
body = (pagekit.head(f"Routes by {g['name']}", lede, [("Trails", "/"), ("Lists", "/lists/"), ("Authors", INDEX)])
|
||||
+ f"""<div class="container section place">
|
||||
<h2 id="routes">{'The route' if n == 1 else 'The routes'}</h2>
|
||||
{pagekit.table(heads, rows, caption=f"Routes by {g['name']}")}
|
||||
{shared_note}
|
||||
<h2 id="in-brief">{'About the route' if n == 1 else 'About each route'}</h2>
|
||||
{briefs}
|
||||
{more}
|
||||
{home.overview_map(routes, f"Map of the routes by {g['name']}")}
|
||||
{nav}
|
||||
<nav class="region-nav" aria-label="Related pages"><a href="/routes/">All routes</a> · <a href="{INDEX}">All route authors</a></nav>
|
||||
</div>""")
|
||||
name = g["name"]
|
||||
options = [f"Routes by {name}: {_plural(n, 'Long Hiking Route')}", f"Routes by {name}"]
|
||||
title = next((o for o in options if len(o) <= TITLE_LIMIT), common.cut_at_word(options[-1], TITLE_LIMIT))
|
||||
desc = regions._fit([f"{_plural(n, 'long hiking route')} by or with {name}, with length, where it runs, usual time and where it is published.",
|
||||
f"{_plural(n, 'route')} by {name}."])
|
||||
return title, desc, Markup(body), home.has_overview_map(routes), routes, person_jsonld(g, site, sites)
|
||||
|
||||
|
||||
def person_jsonld(g, site, sites):
|
||||
"""The author as a Person, only where authors.toml says the credit is a person."""
|
||||
if g["kind"] != "person":
|
||||
return None
|
||||
node = {"@type": "Person", "@id": seo.url_of(site, path(g)) + "#author", "name": g["name"],
|
||||
"url": sites[0][1] if sites else None, "sameAs": [u for _, u in sites] or None}
|
||||
return seo._clean(node)
|
||||
+196
-24
@@ -11,13 +11,17 @@ only when it is useful with today's trails:
|
||||
MAX_SHARE at most this share of all trails (more is nearly everything)
|
||||
|
||||
Every list has its page at /lists/<key>/, except Routes, which keeps /routes/.
|
||||
A list with a `noun` also has a page for each state or province where at least
|
||||
MIN_SIZE of its trails are, and fewer than MAX_SHARE of that place's (olt/placefacets.py).
|
||||
A list belongs to a `group` (GROUPS), the heading it sits under on /lists/.
|
||||
"""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
from typing import Callable, Optional
|
||||
|
||||
from . import common, facets, words
|
||||
from . import common, facets, hike, words
|
||||
|
||||
MIN_SIZE = 4
|
||||
MIN_SIZE = 5
|
||||
MAX_SHARE = 0.75
|
||||
|
||||
# The two lists defined by length are set in miles; membership compares the
|
||||
@@ -40,6 +44,19 @@ class List:
|
||||
# The page's <title> before the site name, in the words people search with; {n} is
|
||||
# the number of trails. Empty: the list's own title with the count.
|
||||
page_title: str = ""
|
||||
# The heading it sits under on /lists/ (a key of GROUPS).
|
||||
group: str = ""
|
||||
# The words for this kind of trail in a place page's title: "Loop Hiking Trails" gives
|
||||
# "Loop Hiking Trails in Colorado: 6 Trails". Empty: no page for each place.
|
||||
noun: str = ""
|
||||
# (list's trails, all trails) -> a plain sentence or two that says what the list covers
|
||||
# where that is not every trail: how many have the fact the list is built on.
|
||||
note: Optional[Callable] = None
|
||||
# The page opens with a table of key figures for its trails (olt/standing.py): for a short
|
||||
# list of named standing, where a reader compares the trails.
|
||||
table: bool = False
|
||||
# A larger least size than MIN_SIZE, where the list is thin by nature (a month's list).
|
||||
min_size: int = 0
|
||||
|
||||
def search_title(self, n):
|
||||
return (self.page_title or f"{self.title}: {{n}} Trails").format(n=n)
|
||||
@@ -56,55 +73,205 @@ def _band(key):
|
||||
# The terrain as an adjective, for a list's page title ("Coastal Hiking Trails").
|
||||
TERRAIN_ADJECTIVE = {"coast": "Coastal", "lakes": "Lake"}
|
||||
|
||||
# The headings on /lists/, in order: (key, heading, one sentence under it).
|
||||
GROUPS = (
|
||||
("standing", "By standing", "What kind of trail it is: named by Congress, certified, or a route a hiker published."),
|
||||
("length", "By length", "Trails sorted into length bands. Lengths are the published figures."),
|
||||
("time", "By time to walk", "How long the whole trail usually takes, as a source states it or as estimated from the length."),
|
||||
("walking", "By kind of walking", "Loops, high routes, walking with no trail, and trails not yet finished."),
|
||||
("terrain", "By terrain", "The main kinds of country a trail crosses."),
|
||||
("holder", "By who looks after it", "Trails whose designation names the holder."),
|
||||
("month", "By month", "Trails whose season on file includes the month. Only some trails have a season."),
|
||||
("where", "By country and GPX", "Where a trail is, and whether its page has a track to download."),
|
||||
)
|
||||
|
||||
# A month's list is shown with at least this many trails.
|
||||
MONTH_MIN = 8
|
||||
|
||||
# Days: a weekend or a long weekend is up to four days.
|
||||
WEEKEND_DAYS = 4
|
||||
|
||||
|
||||
def _mid_days(rec):
|
||||
lo, hi, _ = facets.time_days(rec)
|
||||
return (lo + hi) / 2
|
||||
|
||||
|
||||
def _mi(n):
|
||||
return round(words.km_to_mi(n))
|
||||
|
||||
|
||||
def time_note(recs, records):
|
||||
"""How many of a time list's trails have a time a source states, and how the rest were estimated."""
|
||||
est = sum(1 for r in recs if facets.time_days(r)[2])
|
||||
stated = len(recs) - est
|
||||
(a, b), (c, d) = facets.PACE_KM, facets.PACE_KM_CROSS
|
||||
how = (f"estimated from the length, at {_mi(a)} to {_mi(b)} miles a day, or {_mi(c)} to {_mi(d)} "
|
||||
f"where much of it is cross-country")
|
||||
if not est:
|
||||
return f"A source states the time for all {stated}."
|
||||
if not stated:
|
||||
return f"No source states the time for these, so each is {how}."
|
||||
return f"A source states the time for {stated} of these. For the other {est} it is {how}."
|
||||
|
||||
|
||||
def _month_list(m):
|
||||
name = facets.MONTHS[m - 1]
|
||||
return List(f"hike-in-{name.lower()}", f"Hiking in {name}",
|
||||
f"Trails whose season on file includes {name}.",
|
||||
lambda r, m=m: m in facets.months(r),
|
||||
page_title=f"Long Trails to Hike in {name}: {{n}} Trails", group="month", note=month_note(name),
|
||||
min_size=MONTH_MIN)
|
||||
|
||||
|
||||
def month_note(name):
|
||||
def note(recs, records):
|
||||
have = sum(1 for r in records if facets.months(r))
|
||||
return (f"Only {have} of the {len(records)} trails have a season on file, so this page covers those "
|
||||
f"{have}. It is not every trail that can be walked in {name}.")
|
||||
return note
|
||||
|
||||
|
||||
def _high_route(rec):
|
||||
text = " ".join((rec.get("name", ""), rec.get("common_name", ""), rec.get("designation", "")))
|
||||
return bool(re.search(r"\bhigh route\b", text, re.I))
|
||||
|
||||
|
||||
def _designation(rx, routes=True):
|
||||
"""A test on the designation field: it names the holder or the standing, as the record words it."""
|
||||
pattern = re.compile(rx, re.I)
|
||||
return lambda r: bool(pattern.search(r.get("designation", ""))) and (routes or facets.kind(r) != "route")
|
||||
|
||||
|
||||
def _length_band(lo_mi, hi_mi):
|
||||
lo, hi = lo_mi * words.KM_PER_MI, hi_mi * words.KM_PER_MI
|
||||
return lambda r: lo <= r["length_km"] < hi
|
||||
|
||||
|
||||
MID_MI = 200
|
||||
MID_KM = MID_MI * words.KM_PER_MI
|
||||
HALF_MI = 500
|
||||
LISTS = (
|
||||
List("national-scenic-trails", "National Scenic Trails",
|
||||
"The long trails the United States Congress has named National Scenic Trails.",
|
||||
facets.is_national, page_title="National Scenic Trails: {n} Long Hiking Trails"),
|
||||
facets.is_national, page_title="National Scenic Trails: {n} Long Hiking Trails", group="standing", table=True),
|
||||
List("national-recreation-trails", "National Recreation Trails",
|
||||
"Trails whose designation says they are National Recreation Trails.",
|
||||
_designation(r"National Recreation Trail"),
|
||||
page_title="National Recreation Trails: {n} Long Hiking Trails", group="standing", table=True),
|
||||
List("routes", "Routes", facets.ROUTE_DEFINITION,
|
||||
lambda r: facets.kind(r) == "route", page_title="Long Hiking Routes by Author: {n} Routes"),
|
||||
lambda r: facets.kind(r) == "route", page_title="Long Hiking Routes by Author: {n} Routes",
|
||||
group="standing", noun="Long Hiking Routes"),
|
||||
List("high-routes", "High routes",
|
||||
"Routes whose own name says High Route: through high country, often off the trail.",
|
||||
_high_route, page_title="High Routes: {n} Long Hiking Routes", group="walking"),
|
||||
List("longest", "The longest",
|
||||
f"Trails of {LONG_MI:,} miles ({_km(LONG_MI)} km) or more.",
|
||||
lambda r: r["length_km"] >= LONG_KM, sort="length-desc",
|
||||
page_title=f"Longest Hiking Trails: {{n}} Trails of {LONG_MI:,}+ Miles"),
|
||||
page_title=f"Longest Hiking Trails: {{n}} Trails of {LONG_MI:,}+ Miles", group="length"),
|
||||
List("500-to-1000-miles", f"{HALF_MI} to {LONG_MI:,} miles",
|
||||
f"Trails of {HALF_MI} miles ({_km(HALF_MI)} km) or more and shorter than {LONG_MI:,} miles ({_km(LONG_MI)} km).",
|
||||
_length_band(HALF_MI, LONG_MI), sort="length-desc",
|
||||
page_title=f"Hiking Trails of {HALF_MI} to {LONG_MI:,} Miles: {{n}} Long Trails", group="length",
|
||||
noun=f"Hiking Trails of {HALF_MI} to {LONG_MI:,} Miles"),
|
||||
List("200-to-500-miles", f"{MID_MI} to {HALF_MI} miles",
|
||||
f"Trails of {MID_MI} miles ({_km(MID_MI)} km) or more and shorter than {HALF_MI} miles ({_km(HALF_MI)} km).",
|
||||
_length_band(MID_MI, HALF_MI), sort="length-desc",
|
||||
page_title=f"Hiking Trails of {MID_MI} to {HALF_MI} Miles: {{n}} Long Trails", group="length",
|
||||
noun=f"Hiking Trails of {MID_MI} to {HALF_MI} Miles"),
|
||||
List("100-to-200-miles", f"{SHORT_MI} to {MID_MI} miles",
|
||||
f"Trails of {SHORT_MI} miles ({_km(SHORT_MI)} km) or more and shorter than {MID_MI} miles ({_km(MID_MI)} km).",
|
||||
_length_band(SHORT_MI, MID_MI), sort="length-desc",
|
||||
page_title=f"Hiking Trails of {SHORT_MI} to {MID_MI} Miles: {{n}} Long Trails", group="length",
|
||||
noun=f"Hiking Trails of {SHORT_MI} to {MID_MI} Miles"),
|
||||
List("under-100-miles", f"Under {SHORT_MI} miles",
|
||||
f"Trails shorter than {SHORT_MI} miles ({_km(SHORT_MI)} km).",
|
||||
lambda r: r["length_km"] < SHORT_KM, sort="length-asc",
|
||||
page_title=f"Hiking Trails Under {SHORT_MI} Miles: {{n}} Long Trails"),
|
||||
page_title=f"Hiking Trails Under {SHORT_MI} Miles: {{n}} Long Trails", group="length",
|
||||
noun=f"Hiking Trails Under {SHORT_MI} Miles"),
|
||||
List("under-200-miles", f"Under {MID_MI} miles",
|
||||
f"Trails shorter than {MID_MI} miles ({_km(MID_MI)} km): the two shortest bands together.",
|
||||
lambda r: r["length_km"] < MID_KM, sort="length-asc",
|
||||
page_title=f"Thru-Hikes Under {MID_MI} Miles: {{n}} Long Trails", group="length"),
|
||||
List("weekend", "A weekend or long weekend",
|
||||
f"Trails that take {WEEKEND_DAYS} days or fewer to walk whole.",
|
||||
lambda r: _mid_days(r) <= WEEKEND_DAYS, sort="time-asc",
|
||||
page_title="Long Trails to Hike in a Weekend: {n} Trails", group="time", note=time_note),
|
||||
List("a-week-or-less", "A week or less",
|
||||
"Trails most people walk in a week or less, as a source states it or as estimated from the length.",
|
||||
_band("week"), sort="time-asc", page_title="Long Trails to Hike in a Week or Less: {n} Trails"),
|
||||
_band("week"), sort="time-asc", page_title="Long Trails to Hike in a Week or Less: {n} Trails",
|
||||
group="time", note=time_note),
|
||||
List("one-to-two-weeks", "One to two weeks",
|
||||
"Trails that take one to two weeks, as a source states it or as estimated from the length.",
|
||||
_band("two-weeks"), sort="time-asc", page_title="Long Trails to Hike in One to Two Weeks: {n} Trails"),
|
||||
_band("two-weeks"), sort="time-asc", page_title="Long Trails to Hike in One to Two Weeks: {n} Trails",
|
||||
group="time", note=time_note),
|
||||
List("two-to-four-weeks", "Two weeks to a month",
|
||||
"Trails that take two to four weeks to walk whole.",
|
||||
_band("month"), sort="time-asc", page_title="Long Trails to Hike in 2 to 4 Weeks: {n} Trails",
|
||||
group="time", note=time_note),
|
||||
List("a-month-or-more", "A month or more",
|
||||
"Trails that take more than four weeks to walk whole.",
|
||||
lambda r: facets.time_band(r) in ("months", "long"), sort="time-asc",
|
||||
page_title="Long Trails That Take a Month or More: {n} Trails", group="time", note=time_note),
|
||||
List("loops", "Loops", "Trails that finish where they start.",
|
||||
lambda r: facets.shape(r) == "loop", page_title="Loop Hiking Trails: {n} Long Trail Loops"),
|
||||
List("with-gpx", "With a GPX to download",
|
||||
"Trails with a GPX file of the track on their page.",
|
||||
facets.gpx_here, page_title="Long Trails with a GPX to Download: {n} Trails"),
|
||||
List("canada", "In Canada", "Trails in Canada, or crossing into it.",
|
||||
lambda r: "CA" in common.countries(r), page_title="Hiking Trails in Canada: {n} Long Trails"),
|
||||
List("united-states", "In the United States", "Trails in the United States, or crossing into it.",
|
||||
lambda r: "US" in common.countries(r), page_title="Hiking Trails in the United States: {n} Long Trails"),
|
||||
lambda r: facets.shape(r) == "loop", page_title="Loop Hiking Trails: {n} Long Trail Loops",
|
||||
group="walking", noun="Loop Hiking Trails"),
|
||||
List("off-trail", "Cross-country",
|
||||
"Trails with stretches of walking where there is no trail.",
|
||||
lambda r: facets.walking(r) in facets.CROSS_COUNTRY,
|
||||
page_title="Cross-Country Hiking: {n} Long Trails and Routes"),
|
||||
page_title="Cross-Country Hiking: {n} Long Trails and Routes", group="walking",
|
||||
noun="Cross-Country Hiking"),
|
||||
List("mostly-cross-country", "Mostly cross-country",
|
||||
"Trails where there is no trail for most of the way.",
|
||||
lambda r: facets.walking(r) == "mostly-cross-country",
|
||||
page_title="Mostly Cross-Country Hiking Routes: {n} Long Trails", group="walking"),
|
||||
List("unfinished", "Not yet finished",
|
||||
"Trails that are not complete on the ground.",
|
||||
lambda r: bool(hike.table(r).get("unfinished")),
|
||||
page_title="Unfinished Long Trails: {n} Trails Not Yet Complete", group="walking"),
|
||||
List("parks-canada", "Parks Canada",
|
||||
"Trails whose designation names Parks Canada.",
|
||||
_designation(r"Parks Canada"), page_title="Parks Canada Hiking Trails: {n} Long Trails", group="holder"),
|
||||
List("forest-service", "Forest Service",
|
||||
"Trails whose designation names the Forest Service.",
|
||||
_designation(r"Forest Service|USFS"), page_title="Forest Service Hiking Trails: {n} Long Trails",
|
||||
group="holder"),
|
||||
List("state-and-provincial-parks", "State and provincial parks",
|
||||
"Trails whose designation names a state or provincial park.",
|
||||
_designation(r"\b(state|provincial) parks?\b"),
|
||||
page_title="State and Provincial Park Trails: {n} Long Trails", group="holder"),
|
||||
List("clubs-and-associations", "Clubs and associations",
|
||||
"Trails, not routes, whose designation names a club, association, conservancy or similar group.",
|
||||
_designation(r"Association|Club|Conservancy|Alliance|Foundation|Society|Conference|Council|Trust",
|
||||
routes=False),
|
||||
page_title="Trails Kept by Clubs and Associations: {n} Trails", group="holder"),
|
||||
List("with-gpx", "With a GPX to download",
|
||||
"Trails with a GPX file of the track on their page.",
|
||||
facets.gpx_here, page_title="Long Trails with a GPX to Download: {n} Trails", group="where",
|
||||
noun="Hiking Trails with a GPX"),
|
||||
List("canada", "In Canada", "Trails in Canada, or crossing into it.",
|
||||
lambda r: "CA" in common.countries(r), page_title="Hiking Trails in Canada: {n} Long Trails",
|
||||
group="where"),
|
||||
List("united-states", "In the United States", "Trails in the United States, or crossing into it.",
|
||||
lambda r: "US" in common.countries(r), page_title="Hiking Trails in the United States: {n} Long Trails",
|
||||
group="where"),
|
||||
) + tuple(
|
||||
List(f"terrain-{t}", label, f"Trails with {t} among their main terrain.",
|
||||
lambda r, t=t: t in facets.terrain(r),
|
||||
page_title=f"{TERRAIN_ADJECTIVE.get(t, label)} Hiking Trails: {{n}} Long Trails")
|
||||
page_title=f"{TERRAIN_ADJECTIVE.get(t, label)} Hiking Trails: {{n}} Long Trails", group="terrain",
|
||||
noun=f"{TERRAIN_ADJECTIVE.get(t, label)} Hiking Trails")
|
||||
for t, label in words.TERRAIN.items()
|
||||
)
|
||||
) + tuple(_month_list(m) for m in range(1, 13))
|
||||
|
||||
|
||||
def members(lst, records):
|
||||
return facets.sort_records([r for r in records if lst.test(r)], lst.sort)
|
||||
|
||||
|
||||
def is_shown(n, total):
|
||||
def is_shown(n, total, least=0):
|
||||
"""The threshold rule: a list is shown when it holds at least MIN_SIZE
|
||||
trails and no more than MAX_SHARE of all of them."""
|
||||
return n >= MIN_SIZE and n <= MAX_SHARE * total
|
||||
trails (or `least`, where the list asks for more) and no more than MAX_SHARE of all of them."""
|
||||
return n >= max(MIN_SIZE, least) and n <= MAX_SHARE * total
|
||||
|
||||
|
||||
def shown(records):
|
||||
@@ -112,7 +279,7 @@ def shown(records):
|
||||
out = []
|
||||
for lst in LISTS:
|
||||
recs = members(lst, records)
|
||||
if is_shown(len(recs), len(records)):
|
||||
if is_shown(len(recs), len(records), lst.min_size):
|
||||
out.append((lst, recs))
|
||||
return out
|
||||
|
||||
@@ -121,5 +288,10 @@ def by_key(key):
|
||||
return next(lst for lst in LISTS if lst.key == key)
|
||||
|
||||
|
||||
def facet_lists():
|
||||
"""The lists that also have a page for each place (those with a noun)."""
|
||||
return [lst for lst in LISTS if lst.noun]
|
||||
|
||||
|
||||
def path(lst):
|
||||
return "/routes/" if lst.key == "routes" else f"/lists/{lst.key}/"
|
||||
@@ -73,3 +73,14 @@ def stored_fingerprint(path):
|
||||
break
|
||||
pos += 12 + size
|
||||
return ""
|
||||
|
||||
|
||||
def site_lines(site):
|
||||
"""The two texts the site card shows: the site's name and its headline (the tagline, as
|
||||
the home page prints it, with a full stop)."""
|
||||
return site.name, site.tagline.rstrip(".") + "."
|
||||
|
||||
|
||||
def site_fingerprint(site):
|
||||
"""Like fingerprint(), for the site card assets/og.png."""
|
||||
return hashlib.sha1("\n".join(site_lines(site)).encode("utf-8")).hexdigest()[:12]
|
||||
+51
-5
@@ -50,15 +50,18 @@ def partial_short_text(rec):
|
||||
f"{words.length(rec['length_km'], mi=rec['derived']['length_mi'])} published")
|
||||
|
||||
|
||||
# A search result shows about this much. The title limit counts the whole title,
|
||||
# the site name included.
|
||||
TITLE_LIMIT = 65
|
||||
# A search result shows about 60 characters of a title and about 155 of a description; a
|
||||
# social preview shows about 125 characters of a description. The site name is shown by
|
||||
# the search engine on its own line, so " \u00b7 <site name>" is added to the <title> only when
|
||||
# the whole title still has TITLE_LIMIT characters or fewer.
|
||||
TITLE_LIMIT = 60
|
||||
DESCRIPTION_LIMIT = 155
|
||||
SHARE_DESCRIPTION_LIMIT = 125
|
||||
|
||||
|
||||
def title_room(site):
|
||||
"""How many characters a page's own title may have, before " · <site name>"."""
|
||||
return TITLE_LIMIT - len(site.name) - len(" \u00b7 ")
|
||||
"""How many characters a page's own title may have: TITLE_LIMIT, with or without the site name."""
|
||||
return TITLE_LIMIT
|
||||
|
||||
|
||||
def fit_title(options, site):
|
||||
@@ -66,6 +69,49 @@ def fit_title(options, site):
|
||||
return next((o for o in options if len(o) <= title_room(site)), options[-1])
|
||||
|
||||
|
||||
def title_tag(title, site):
|
||||
"""The text of <title>: "<title> \u00b7 <site name>" where that is TITLE_LIMIT characters or
|
||||
fewer, else the title alone."""
|
||||
full = f"{title} \u00b7 {site.name}"
|
||||
return full if len(full) <= TITLE_LIMIT else title
|
||||
|
||||
|
||||
_DANGLING = {"and", "or", "but", "nor", "with", "to", "of", "the", "a", "an", "in", "on", "at", "by",
|
||||
"for", "from", "as", "than", "that", "which", "is", "are", "was", "were", "about",
|
||||
"across", "through", "over", "under", "between", "into", "near", "via"}
|
||||
_ABBREVIATIONS = {"st", "mt", "mts", "ft", "no", "vs", "u.s", "d.c", "dr", "jr", "sr", "approx", "e.g", "i.e"}
|
||||
|
||||
|
||||
def share_description(text, limit=SHARE_DESCRIPTION_LIMIT):
|
||||
"""text for a social preview: at most `limit` characters, cut from the search description at the
|
||||
end of a sentence where one falls past half the limit, else at the end of a word, with an
|
||||
ellipsis. A cut never leaves a comma, a colon or a conjunction (or other joining word) last."""
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
best = 0
|
||||
for m in re.finditer(r"[.!?](?= )", text[:limit + 1]):
|
||||
if m.end() > limit:
|
||||
break
|
||||
last = text[:m.start()].rsplit(" ", 1)[-1].lower().rstrip(".")
|
||||
if last in _ABBREVIATIONS:
|
||||
continue
|
||||
best = m.end()
|
||||
if best >= limit // 2:
|
||||
return text[:best]
|
||||
head = text[:limit - 1]
|
||||
if text[limit - 1] != " ":
|
||||
head = head.rsplit(" ", 1)[0] if " " in head else head
|
||||
head = head.rstrip(" ,;:.")
|
||||
while True:
|
||||
word = head.rsplit(" ", 1)[-1].lower().rstrip(",;:")
|
||||
if " " in head and (word in _DANGLING or head[-1] in ",;:"):
|
||||
head = head.rsplit(" ", 1)[0].rstrip(" ,;:.")
|
||||
else:
|
||||
break
|
||||
return head + "\u2026"
|
||||
|
||||
|
||||
def plain_name(rec):
|
||||
"""The name hikers use (common_name) where the record has one, else its name. Plain text."""
|
||||
return rec.get("common_name") or rec["name"]
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""The small editorial data files at the top of the repository, read for the pages built from them.
|
||||
|
||||
glossary.toml [[term]] the Glossary page (olt/reference.py)
|
||||
collections.toml [[collection]] named sets of trails set side by side (olt/standing.py)
|
||||
authors.toml [[author]] route authors credited in more than one form (olt/authors.py)
|
||||
|
||||
Each is checked by tools/validate.py and described in docs/schema.md. Like left-out.toml, a file
|
||||
is looked for in the repository being built and then in this one, so a test repository without
|
||||
one still builds.
|
||||
"""
|
||||
import os
|
||||
import tomllib
|
||||
|
||||
REAL_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
def load(repo_root, name, table):
|
||||
"""The array of tables `table` in file `name`, or []."""
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
path = os.path.join(base or REAL_ROOT, name)
|
||||
if os.path.isfile(path):
|
||||
with open(path, "rb") as f:
|
||||
return tomllib.load(f).get(table) or []
|
||||
return []
|
||||
|
||||
|
||||
def glossary(repo_root):
|
||||
return load(repo_root, "glossary.toml", "term")
|
||||
|
||||
|
||||
def collections(repo_root):
|
||||
return load(repo_root, "collections.toml", "collection")
|
||||
|
||||
|
||||
def authors(repo_root):
|
||||
return load(repo_root, "authors.toml", "author")
|
||||
+26
-1
@@ -83,7 +83,7 @@ def link_requests(html, site):
|
||||
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
|
||||
contact = site.contact or site.repo_url
|
||||
if issue:
|
||||
for phrase in ("Open an issue", "open an issue", "opening an issue"):
|
||||
html = _link_text(html, phrase, issue)
|
||||
@@ -284,6 +284,30 @@ def _count_line(records, key, value):
|
||||
return sum(1 for r in records if str(r.get(key, "")) == value)
|
||||
|
||||
|
||||
def maintainer_section(site):
|
||||
"""The About page's "Who maintains this", from site.toml and facts the repository holds:
|
||||
the name and the profile page, the licence, the sources, how a correction is made, and what
|
||||
the site does not do. "" when site.toml names no maintainer. No email address, no biography."""
|
||||
if not site.maintainer_name:
|
||||
return ""
|
||||
who = esc(site.maintainer_name)
|
||||
if site.maintainer_url:
|
||||
who = f'<a href="{esc(site.maintainer_url)}">{who}</a>'
|
||||
ask = "open an issue on GitHub"
|
||||
if site.contact:
|
||||
ask = f'<a href="{esc(site.contact)}">open an issue on GitHub</a>'
|
||||
return f"""<section aria-labelledby="who-maintains"><h2 id="who-maintains">Who maintains this</h2>
|
||||
<p>{esc(site.name)} is maintained by {who}. It is an open project: the data, the code and every change are in a public repository.</p>
|
||||
<ul>
|
||||
<li>The records and the compiled index are public domain (CC0 1.0). Each track keeps the licence of its source.</li>
|
||||
<li>Every fact in a record names the page it was read on, and each record keeps a history of what changed and why.</li>
|
||||
<li>To correct a fact, suggest a trail or ask for a track or logo to be removed, {ask}. Every trail page has its own “Report a problem” link.</li>
|
||||
<li>The site has no ads, no accounts, no tracking and no analytics. Your theme, units and saved trails stay in your own browser. Maps load their tiles from OpenFreeMap.</li>
|
||||
</ul>
|
||||
</section>
|
||||
"""
|
||||
|
||||
|
||||
def about_page(records, site, repo_root):
|
||||
"""(title, description, body) for /about/: the hub for the project and the dataset."""
|
||||
readme = read_doc(repo_root, "README.md")
|
||||
@@ -344,6 +368,7 @@ site calls them trails.</p>
|
||||
{what}
|
||||
</section>
|
||||
|
||||
{maintainer_section(site)}
|
||||
<section aria-labelledby="how-trails-are-chosen"><h2 id="how-trails-are-chosen">How trails are chosen</h2>
|
||||
<p>A trail is listed when it is a named, continuous walk, or a named loop, of at least 50 miles (80 km)
|
||||
in the United States or Canada. It is either an official trail, looked after as one trail by a land agency or
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Fingerprinted site assets: the stylesheet, scripts, fonts and map libraries, served
|
||||
from /immutable/ under names that carry a hash of their content.
|
||||
|
||||
A file named for its own content never changes, so it can be cached for a year
|
||||
(web/static/_headers: /immutable/* is "public, max-age=31536000, immutable") and a
|
||||
changed file gets a new name, so a revisit never runs an old script against a new
|
||||
page. Pages (olt/layout.py) ask for each file's address with url(); the build
|
||||
(web/build.py) writes the files with publish() once the pages are written.
|
||||
|
||||
Only these files are fingerprinted; everything else under /assets/ (the icons, the
|
||||
social card, the base-map style, licence texts) keeps its address and revalidates.
|
||||
|
||||
The hash is the first 10 hex digits of SHA-256 of the content as served. The
|
||||
stylesheet names the fonts and the contour picture, so those are hashed first and
|
||||
the stylesheet's own hash covers the addresses written into it.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
|
||||
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ASSETS_DIR = os.path.join(WEB_DIR, "assets")
|
||||
DIR = "/immutable/" # the one directory the files are served from, flat
|
||||
|
||||
# Site paths (under /assets/) of the files that are fingerprinted.
|
||||
STYLESHEET = "/assets/style.css"
|
||||
FILES = (
|
||||
STYLESHEET,
|
||||
"/assets/app.js",
|
||||
"/assets/prefs.js",
|
||||
"/assets/contours.svg",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-400-latin.woff2",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-500-latin.woff2",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-600-latin.woff2",
|
||||
"/assets/fonts/source-serif-4-italic-latin.woff2",
|
||||
"/assets/fonts/source-serif-4-latin.woff2",
|
||||
"/assets/vendor/maplibre-gl/maplibre-gl.css",
|
||||
"/assets/vendor/maplibre-gl/maplibre-gl.js",
|
||||
"/assets/vendor/maplibre-contour/maplibre-contour.js",
|
||||
)
|
||||
# What the stylesheet names, as it writes it: url("fonts/x.woff2") and url("contours.svg").
|
||||
_CSS_URL = re.compile(r'url\("([^"]+)"\)')
|
||||
|
||||
HASH_LEN = 10
|
||||
_cache = {}
|
||||
|
||||
|
||||
def _source(path):
|
||||
return os.path.join(ASSETS_DIR, *path[len("/assets/"):].split("/"))
|
||||
|
||||
|
||||
def _content(path):
|
||||
"""The bytes the file is served with: the stylesheet with its font and picture
|
||||
addresses fingerprinted, every other file as it is."""
|
||||
with open(_source(path), "rb") as f:
|
||||
data = f.read()
|
||||
if path != STYLESHEET:
|
||||
return data
|
||||
|
||||
def rewrite(m):
|
||||
target = "/assets/" + m.group(1)
|
||||
return f'url("{_name(target)}")' if target in FILES else m.group(0)
|
||||
return _CSS_URL.sub(rewrite, data.decode("utf-8")).encode("utf-8")
|
||||
|
||||
|
||||
def _name(path):
|
||||
"""The file name (no directory) of a fingerprinted file."""
|
||||
# Keyed on every file's time: the stylesheet's content depends on the fonts and picture it names.
|
||||
key = (path, tuple(os.path.getmtime(_source(p)) for p in FILES))
|
||||
if key not in _cache:
|
||||
digest = hashlib.sha256(_content(path)).hexdigest()[:HASH_LEN]
|
||||
stem, ext = os.path.splitext(os.path.basename(path))
|
||||
_cache[key] = f"{stem}.{digest}{ext}"
|
||||
return _cache[key]
|
||||
|
||||
|
||||
def url(path):
|
||||
"""The address to use for an asset: /immutable/<name>.<hash>.<ext> for a
|
||||
fingerprinted file, the path itself for any other. The stylesheet's own
|
||||
references are relative, so they resolve inside /immutable/."""
|
||||
if path not in FILES:
|
||||
return path
|
||||
return DIR + _name(path)
|
||||
|
||||
|
||||
def publish(out_dir):
|
||||
"""Write the fingerprinted files to <out>/immutable/ and take the originals out
|
||||
of <out>/assets/, so no page can reach a file under both addresses. Returns the
|
||||
number of files written. Run after the pages step has copied web/assets/."""
|
||||
dest = os.path.join(out_dir, DIR.strip("/"))
|
||||
if os.path.isdir(dest):
|
||||
for name in os.listdir(dest):
|
||||
os.remove(os.path.join(dest, name))
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
for path in FILES:
|
||||
with open(os.path.join(dest, _name(path)), "wb") as f:
|
||||
f.write(_content(path))
|
||||
original = os.path.join(out_dir, "assets", *path[len("/assets/"):].split("/"))
|
||||
if os.path.isfile(original):
|
||||
os.remove(original)
|
||||
return len(FILES)
|
||||
+12
-4
@@ -121,13 +121,18 @@ def gpx_cell(rec):
|
||||
return f'<span class="line__status">{common.SWATCH_NONE}{esc(facets.GPX_SHORT[status])}</span>'
|
||||
|
||||
|
||||
def entry(rec, *, level=3, extra="", routes_list=False, hidden=False):
|
||||
# The first rows of a list are on the first screen: their logos are not lazy-loaded.
|
||||
EAGER_ROWS = 4
|
||||
|
||||
|
||||
def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=False):
|
||||
"""One trail in a list. Its data-* attributes drive the filters in app.js.
|
||||
|
||||
level: the heading level of the trail's name. extra: HTML placed last in the row.
|
||||
routes_list: the Routes list, whose "By <author>" headings already say what the
|
||||
row's Route badge and "Route by" line would repeat; both are left out there.
|
||||
hidden: written hidden, for app.js to show (the Saved page).
|
||||
eager: the logo is not lazy-loaded (a row of the first screen).
|
||||
|
||||
The Save star follows the name in the markup (so it is the next stop for the
|
||||
keyboard) but is drawn under the logo, out of the row's flow (style.css
|
||||
@@ -166,7 +171,7 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False):
|
||||
if hidden:
|
||||
attrs += " hidden"
|
||||
return f"""<li class="entry"{attrs}>
|
||||
{common.plate(rec)}
|
||||
{common.plate(rec, eager=eager)}
|
||||
<div class="entry__body">{kicker}
|
||||
<{h} class="entry__name"><a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a>{abbr_html}</{h}>
|
||||
{common.save_button(rec)}{by}{desc_html}
|
||||
@@ -444,10 +449,13 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
|
||||
noun = ("route" if only_routes else "trail") + ("" if total == 1 else "s")
|
||||
lists = ""
|
||||
every = ' data-every-trail' if finder or saved else ""
|
||||
seen = 0
|
||||
for heading, items, extra_fn in groups:
|
||||
level = top + 1 if heading else top
|
||||
rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "",
|
||||
routes_list=routes_list, hidden=saved) for r in items)
|
||||
routes_list=routes_list, hidden=saved,
|
||||
eager=not saved and seen + i < EAGER_ROWS) for i, r in enumerate(items))
|
||||
seen += len(items)
|
||||
if heading:
|
||||
lists += f'\n <h{top} class="results__group">{heading}</h{top}>'
|
||||
list_id = ' id="entries"' if finder else ""
|
||||
@@ -613,7 +621,7 @@ def render(records, site):
|
||||
return f"""<section class="hero hero--short hero--home" aria-labelledby="hero-title">
|
||||
<div class="container hero__inner">
|
||||
<h1 id="hero-title" class="lockup"><img class="lockup__mark" src="/assets/favicon.svg" alt="" width="96" height="96">{esc(site.name)}<span class="vh">: long-distance hiking trails of the United States and Canada</span></h1>
|
||||
<p class="hero__tagline">Long-distance hiking trails of the United States and Canada.</p>
|
||||
<p class="hero__tagline">{esc(site.tagline.rstrip("."))}.</p>
|
||||
<ul class="hero__tags">
|
||||
<li><a href="#finder">Filters</a></li>
|
||||
<li><a href="/lists/with-gpx/">GPX</a></li>
|
||||
|
||||
+38
-23
@@ -18,7 +18,7 @@ scripts or styles (the Content-Security-Policy forbids them).
|
||||
import json
|
||||
import os
|
||||
|
||||
from . import common, seo, site as site_settings
|
||||
from . import common, fingerprint, seo, site as site_settings
|
||||
from .markup import Markup, attrs, esc, json_block
|
||||
|
||||
NAV = (
|
||||
@@ -35,15 +35,21 @@ NAV_PARENT = {"/trails/": "/", "/lists/": "/", "/routes/": "/",
|
||||
|
||||
FEED_PATH = "/feed.xml" # the Atom feed of the changelog (olt/feed.py)
|
||||
|
||||
# The fonts every page draws above the fold: the body face and the three weights of the
|
||||
# condensed sans (labels, tiles, headings). A weight that arrives after the first paint swaps
|
||||
# in with different letter widths, and the page shifts as the lines re-wrap (the home page's
|
||||
# row of lists moved by 0.15 before the 500 and 600 were here).
|
||||
FONT_PRELOADS = (
|
||||
"/assets/fonts/source-serif-4-latin.woff2",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-400-latin.woff2",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-500-latin.woff2",
|
||||
"/assets/fonts/ibm-plex-sans-condensed-600-latin.woff2",
|
||||
)
|
||||
MAPLIBRE_CSS = "/assets/vendor/maplibre-gl/maplibre-gl.css"
|
||||
MAPLIBRE_JS = "/assets/vendor/maplibre-gl/maplibre-gl.js"
|
||||
# The outdoor map of the trail pages: its style, named on each trail map figure
|
||||
# (data-outdoor) for app.js to fetch, and the contour add-on (maplibre-contour),
|
||||
# loaded on those pages only (layout(outdoor=True)).
|
||||
# loaded with MapLibre on those pages only (layout(outdoor=True)).
|
||||
OUTDOOR_STYLE = "/assets/map/outdoor.json"
|
||||
CONTOUR_JS = "/assets/vendor/maplibre-contour/maplibre-contour.js"
|
||||
|
||||
@@ -139,6 +145,7 @@ def footer(site):
|
||||
<li><a href="/regions/">Places</a></li>
|
||||
<li><a href="/lists/">Lists</a></li>
|
||||
<li><a href="/routes/">Routes</a></li>
|
||||
<li><a href="/authors/">Route authors</a></li>
|
||||
<li class="js-only"><a href="{SAVED_PATH}">Saved trails</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
@@ -146,6 +153,8 @@ def footer(site):
|
||||
<h2 id="footer-project">About</h2>
|
||||
<ul>
|
||||
<li><a href="/about/">About {esc(site.name)}</a></li>
|
||||
<li><a href="/method/">Method: how figures are made</a></li>
|
||||
<li><a href="/glossary/">Glossary</a></li>
|
||||
<li><a href="/data/">Data and downloads</a></li>
|
||||
<li><a href="/sources/">Sources and their terms</a></li>
|
||||
<li><a href="/logos/">Logos</a></li>
|
||||
@@ -189,15 +198,18 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
|
||||
jsonld=None, og_type="website", noindex=False, image="", image_alt="", alternates=()):
|
||||
"""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: site.toml's
|
||||
title the page's own title ("Arizona National Scenic Trail"). The <title>
|
||||
appends " · <site name>" only when the whole is 60 characters or
|
||||
fewer; the share titles (og:title, twitter:title) never carry it. Empty for the home page: site.toml's
|
||||
home_title, or "<name>: <tagline>" where that is not set.
|
||||
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]).
|
||||
description meta description (155 characters); defaults to the site tagline. The share
|
||||
descriptions (og:description, twitter:description) are cut from it to 125.
|
||||
maps True on a page with a .mapfig[data-map]: app.js is given the addresses of
|
||||
MapLibre, and loads it when the map scrolls into view or is touched.
|
||||
outdoor True as well on a page whose map is an outdoor map (a trail
|
||||
page): loads the contour add-on after MapLibre, deferred.
|
||||
page): app.js loads the contour add-on with MapLibre.
|
||||
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.
|
||||
@@ -213,13 +225,15 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
|
||||
"""
|
||||
site = site or site_settings.load()
|
||||
title = title or site.home_title
|
||||
full_title = f"{title} · {site.name}" if title else f"{site.name}: {site.tagline}"
|
||||
tag = common.title_tag(title, site) if title else f"{site.name}: {site.tagline}"
|
||||
share_title = title or tag
|
||||
description = description or site.tagline
|
||||
share_text = common.share_description(description)
|
||||
canonical = "" if noindex else site.canonical(path)
|
||||
head = [
|
||||
'<meta charset="utf-8">',
|
||||
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
||||
f"<title>{esc(full_title)}</title>",
|
||||
f"<title>{esc(tag)}</title>",
|
||||
f'<meta name="description" content="{esc(description)}">',
|
||||
]
|
||||
if noindex:
|
||||
@@ -227,13 +241,13 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
|
||||
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:title" content="{esc(share_title)}">',
|
||||
f'<meta property="og:description" content="{esc(share_text)}">',
|
||||
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_large_image">',
|
||||
f'<meta name="twitter:title" content="{esc(full_title)}">',
|
||||
f'<meta name="twitter:description" content="{esc(description)}">',
|
||||
f'<meta name="twitter:title" content="{esc(share_title)}">',
|
||||
f'<meta name="twitter:description" content="{esc(share_text)}">',
|
||||
]
|
||||
if canonical:
|
||||
head.append(f'<meta property="og:url" content="{esc(canonical)}">')
|
||||
@@ -260,21 +274,22 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
|
||||
]
|
||||
head += [f'<link rel="alternate" type="{esc(kind)}" href="{esc(href)}"{attrs(title=name)}>'
|
||||
for href, kind, name in alternates]
|
||||
head += [f'<link rel="preload" href="{f}" as="font" type="font/woff2" crossorigin>' for f in FONT_PRELOADS]
|
||||
if maps:
|
||||
head.append(f'<link rel="stylesheet" href="{MAPLIBRE_CSS}">')
|
||||
head += [f'<link rel="preload" href="{fingerprint.url(f)}" as="font" type="font/woff2" crossorigin>' for f in FONT_PRELOADS]
|
||||
head += [
|
||||
'<link rel="stylesheet" href="/assets/style.css">',
|
||||
f'<link rel="stylesheet" href="{fingerprint.url("/assets/style.css")}">',
|
||||
# Sets the theme and unit preference before first paint (no inline scripts allowed).
|
||||
'<script src="/assets/prefs.js"></script>',
|
||||
f'<script src="{fingerprint.url("/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>')
|
||||
# The page's one script. A page with a map does not load MapLibre (200 KB of script, 65 KB
|
||||
# of style) with the page: app.js loads these three files itself, when the map scrolls
|
||||
# into view or is touched, from the addresses it is given here.
|
||||
libs = {}
|
||||
if maps:
|
||||
head.append(f'<script src="{MAPLIBRE_JS}" defer></script>')
|
||||
libs = {"data-maplibre-css": MAPLIBRE_CSS, "data-maplibre-js": MAPLIBRE_JS}
|
||||
if outdoor:
|
||||
head.append(f'<script src="{CONTOUR_JS}" defer></script>')
|
||||
libs["data-contour-js"] = CONTOUR_JS
|
||||
libs = "".join(f' {name}="{fingerprint.url(src)}"' for name, src in libs.items())
|
||||
head.append(f'<script src="{fingerprint.url("/assets/app.js")}" defer{libs}></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>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Small pieces the new view pages share: a page heading with a breadcrumb, a table, a ranked row."""
|
||||
from . import words
|
||||
from .markup import Markup, esc
|
||||
|
||||
|
||||
def head(h1, lede_html, crumbs, *, kicker=""):
|
||||
"""The page-head block. crumbs: [(text, href)] leading to this page; lede_html is HTML."""
|
||||
items = "".join(f'<li><a href="{esc(h)}">{esc(t)}</a></li>' for t, h in crumbs)
|
||||
kick = f'<p class="kicker">{esc(kicker)}</p>' if kicker else ""
|
||||
return f"""<div class="page-head"><div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{items}<li aria-current="page">{esc(h1)}</li></ol></nav>
|
||||
<header class="titleblock"><div class="titleblock__text">
|
||||
{kick}<h1>{esc(h1)}</h1>
|
||||
<p class="page-head__lede">{lede_html}</p>
|
||||
</div></header>
|
||||
</div></div>"""
|
||||
|
||||
|
||||
def table(headers, rows, *, caption="", numeric=(), row_heads=False):
|
||||
"""A table in the site's table wrapper. headers: column titles; rows: lists of HTML cells
|
||||
(Markup, or text that is escaped); numeric: column numbers set at the end of the cell;
|
||||
row_heads: the first cell of each row is a row heading."""
|
||||
def cell(i, value, head=False):
|
||||
text = value if isinstance(value, Markup) else esc(value)
|
||||
cls = ' class="num"' if i in numeric else ""
|
||||
if head:
|
||||
return f'<th scope="row"{cls}>{text}</th>'
|
||||
return f"<td{cls}>{text}</td>"
|
||||
cap = f'<caption class="vh">{esc(caption)}</caption>' if caption else ""
|
||||
num = ' class="num"'
|
||||
head = "".join(f'<th scope="col"{num if i in numeric else ""}>{esc(h)}</th>' for i, h in enumerate(headers))
|
||||
body = "".join(
|
||||
"<tr>" + "".join(cell(i, v, head=row_heads and i == 0) for i, v in enumerate(row)) + "</tr>"
|
||||
for row in rows)
|
||||
return Markup(f'<div class="table-wrap"><table>{cap}<thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>')
|
||||
|
||||
|
||||
def trail_link(rec):
|
||||
from . import common
|
||||
return Markup(f'<a href="{esc(common.trail_path(rec))}">{common.name(rec)}</a>')
|
||||
|
||||
|
||||
def ft_per_mile(m_per_km):
|
||||
"""A climb rate as feet per mile and metres per kilometre, in the same unit pair as lengths."""
|
||||
ft_mi = m_per_km * words.M_PER_FT ** -1 * words.KM_PER_MI
|
||||
return Markup(f'<span class="len len--inline"><span class="len__mi">{esc(words.fmt_int(ft_mi))} ft per mile</span>'
|
||||
f'<span class="len__km">{esc(words.fmt_int(m_per_km))} m per km</span></span>')
|
||||
|
||||
|
||||
def append_nav(body, nav_html):
|
||||
"""body with nav_html placed at the end of its last container (the page's closing </div>)."""
|
||||
text = str(body)
|
||||
i = text.rfind("</div>")
|
||||
return Markup(text[:i] + nav_html + text[i:]) if i >= 0 else Markup(text + nav_html)
|
||||
|
||||
|
||||
def more_nav(path, extras):
|
||||
"""A line of links to the other table, change and reference pages: extras is
|
||||
[(group, title, blurb, path, n)] as pages.py builds it for /lists/."""
|
||||
links = " · ".join(f'<a href="{esc(p)}">{esc(t)}</a>' for _, t, _, p, _ in extras if p != path)
|
||||
return (f'<nav class="region-nav" aria-label="More tables and reference pages">More pages: {links} · '
|
||||
f'<a href="/lists/">All lists</a></nav>') if links else ""
|
||||
+113
-12
@@ -3,7 +3,11 @@
|
||||
render_site(records, out_dir, repo_root)
|
||||
|
||||
writes:
|
||||
/assets/... web/assets/ copied verbatim (style.css, app.js, fonts, vendor)
|
||||
/assets/... web/assets/ copied as it is (icons, social card, base-map style), less the
|
||||
files below that are fingerprinted
|
||||
/immutable/... the stylesheet, scripts, fonts and map libraries, each named for a hash of
|
||||
its content; written by web/build.py through olt/fingerprint.py once the
|
||||
pages are, which also removes their copies from /assets/
|
||||
/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
|
||||
@@ -26,14 +30,16 @@ import json
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from . import browse, cards, docs, facets, feed, home, layout, leftout, regions, saved, seo, site as site_settings, thumbs, trail
|
||||
from .markup import esc
|
||||
from . import authors, browse, cards, datafiles, docs, facets, feed, home, layout, leftout, pagekit, placefacets, reference, regions, saved, seo, site as site_settings, standing, thumbs, trail, views
|
||||
|
||||
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."""
|
||||
"""Copy web/assets/ to <out>/assets/, replacing what was there. The fingerprinted files
|
||||
(olt/fingerprint.py) are copied too and taken out again by fingerprint.publish()."""
|
||||
dest = os.path.join(out_dir, "assets")
|
||||
if os.path.isdir(dest):
|
||||
shutil.rmtree(dest)
|
||||
@@ -83,13 +89,14 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
pages = 0
|
||||
dates = {} # page path -> its own date (YYYY-MM-DD), for the sitemap
|
||||
everything = seo.newest(records)
|
||||
author_links = authors.link_map(records, repo_root)
|
||||
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, records)
|
||||
title, description, body, needs_map = trail.render(rec, site, records, author_links=author_links)
|
||||
path = f"/trails/{rec['id']}/"
|
||||
card, card_alt = cards.prepare(rec, out_dir)
|
||||
layout.write_page(out_dir, path, layout.layout(
|
||||
@@ -106,38 +113,132 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
layout.write_page(out_dir, "/404.html", not_found_page(site))
|
||||
pages += 2
|
||||
|
||||
def add(path, title, description, body_html, *, maps=False, jsonld=None, recs=None, date="", alternates=()):
|
||||
"""Write a page. recs: the trails it lists, which give its date and its ItemList."""
|
||||
def add(path, title, description, body_html, *, maps=False, jsonld=None, recs=None, date="", alternates=(), about=None):
|
||||
"""Write a page. recs: the trails it lists, which give its date and its ItemList.
|
||||
about: a node the page is about (an author's Person), added to its graph."""
|
||||
nonlocal pages
|
||||
if recs is not None:
|
||||
jsonld = seo.collection_jsonld(path, site, title=title, description=description, recs=recs)
|
||||
if about:
|
||||
jsonld[0]["about"] = {"@id": about["@id"]}
|
||||
jsonld.append(about)
|
||||
layout.write_page(out_dir, path, layout.layout(
|
||||
title, body_html, path=path, description=description, maps=maps, site=site, jsonld=jsonld,
|
||||
alternates=alternates))
|
||||
dates[path] = date or (seo.newest(recs) if recs is not None else everything)
|
||||
pages += 1
|
||||
|
||||
shown = browse.shown(records)
|
||||
facet_plan = placefacets.plan(records)
|
||||
facets_of_place = placefacets.pages_by_place(facet_plan)
|
||||
t, d, b = regions.regions_index_page(records, site)
|
||||
add("/regions/", t, d, b) # every trail is on it: the newest of them
|
||||
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)
|
||||
here = [(p["lst"].title, p["path"], len(p["recs"])) for p in facets_of_place.get(slug, [])]
|
||||
t, d, b, needs_map = regions.region_page(slug, records, site, facet_pages=here)
|
||||
path = f"/regions/{slug}/"
|
||||
region_paths.append(path)
|
||||
add(path, t, d, b, maps=needs_map, recs=by_slug[slug]["records"])
|
||||
# Pages for one kind of trail in one place (olt/placefacets.py).
|
||||
for p in facet_plan:
|
||||
t, d, b, needs_map = placefacets.page(p, records, site, facet_plan)
|
||||
region_paths.append(p["path"])
|
||||
add(p["path"], t, d, b, maps=needs_map, recs=p["recs"])
|
||||
# The view pages: each is built only when the records give it at least MIN_SIZE trails.
|
||||
view_paths = []
|
||||
labels = {"/": "Every trail", "/lists/": "All lists", "/regions/": "Places", "/data/schema/": "Record schema"}
|
||||
extras = [] # (group, title, blurb, path, how many) for /lists/
|
||||
for lst, _ in shown:
|
||||
labels[browse.path(lst)] = lst.title
|
||||
|
||||
pending = [] # (path, title, description, body, add() options): written once every view is known
|
||||
|
||||
def view(path, group, link_label, blurb, built):
|
||||
"""Hold a view page built as (title, description, body, recs...) and note it for /lists/."""
|
||||
t, d, b = built[:3]
|
||||
recs = built[3] if len(built) > 3 and isinstance(built[3], list) else None
|
||||
pending.append((path, t, d, b, {"recs": recs}))
|
||||
view_paths.append(path)
|
||||
labels[path] = link_label
|
||||
if group:
|
||||
extras.append((group, link_label, blurb, path, len(recs) if recs else 0))
|
||||
|
||||
for c in datafiles.collections(repo_root):
|
||||
built = standing.collection_page(c, records, site)
|
||||
if built:
|
||||
view(standing.collection_path(c), "tables", f"{c['name']} trails compared",
|
||||
f"The {c['name']} trails side by side: length, states, time, high point, climb and season.", built)
|
||||
ranked = []
|
||||
for spec in standing.RANKINGS:
|
||||
built = standing.ranking_page(spec, records, site)
|
||||
if built:
|
||||
path = f"{standing.NUMBERS}{spec[0]}/"
|
||||
ranked.append((path, spec[1], len(built[3])))
|
||||
view(path, "tables", spec[1], f"{len(built[3])} trails with the figure, ranked, with the caveats.", built)
|
||||
if ranked:
|
||||
view(standing.NUMBERS, "tables", "Long trails by the numbers",
|
||||
"The longest and shortest, trails by state and province, and links to the rankings.",
|
||||
standing.numbers_page(records, site, ranked))
|
||||
author_groups = authors.author_pages(records, repo_root)
|
||||
authors_built = any(facets.kind(r) == "route" for r in records)
|
||||
if authors_built:
|
||||
t, d, b, routes = authors.index_page(records, site, repo_root)
|
||||
view(authors.INDEX, "tables", "Route authors", f"The {len(routes)} routes by who published them, and where.",
|
||||
(t, d, b, routes))
|
||||
for g in author_groups:
|
||||
t, d, b, needs_map, routes, person = authors.author_page(g, records, site, author_groups)
|
||||
path = authors.path(g)
|
||||
pending.append((path, t, d, b, {"maps": needs_map, "recs": routes, "about": person}))
|
||||
view_paths.append(path)
|
||||
labels[path] = f"Routes by {g['name']}"
|
||||
built = views.recent_page(records, site)
|
||||
if built:
|
||||
view(views.RECENT, "changes", "Recently added and changed",
|
||||
"The newest additions and the newest changes to what each trail says.", built)
|
||||
built = views.connected_page(records, site)
|
||||
if built:
|
||||
view(views.CONNECTED, "changes", "Linked long trails", "Trails whose own descriptions name another trail.", built)
|
||||
t, d, b = reference.method_page(records, site, repo_root)
|
||||
pending.append((reference.METHOD, t, d, b, {"jsonld": seo.article_jsonld(reference.METHOD, site, title=t, description=d,
|
||||
date=everything)}))
|
||||
view_paths.append(reference.METHOD)
|
||||
labels[reference.METHOD] = "Method"
|
||||
extras.append(("reference", "How the figures are measured", "What each figure means and how far to trust it.", reference.METHOD, 0))
|
||||
glossary = reference.glossary_page(repo_root, labels, site)
|
||||
if glossary:
|
||||
t, d, b, terms = glossary
|
||||
pending.append((reference.GLOSSARY, t, d, b, {"jsonld": seo.glossary_jsonld(
|
||||
reference.GLOSSARY, site, title=t, description=d, terms=terms, date=everything)}))
|
||||
view_paths.append(reference.GLOSSARY)
|
||||
extras.append(("reference", "Glossary", f"{len(terms)} trail terms as this site uses them.", reference.GLOSSARY, len(terms)))
|
||||
for path, t, d, b, options in pending:
|
||||
b = pagekit.append_nav(b, pagekit.more_nav(path, extras) + reference.terms_nav(path, repo_root))
|
||||
add(path, t, d, b, **options)
|
||||
# Lists, each with its figures, related lists and terms.
|
||||
list_paths = []
|
||||
shown = browse.shown(records)
|
||||
for lst, recs in shown:
|
||||
if lst.key == "routes":
|
||||
continue # /routes/ below, built whether or not the list is shown
|
||||
t, d, b, needs_map = regions.list_page(lst, recs, len(records), site)
|
||||
path = browse.path(lst)
|
||||
before = standing.figures_section(recs) if lst.table else ""
|
||||
same = [(o, len(r)) for o, r in shown if o.group == lst.group and o.key != lst.key]
|
||||
after = ""
|
||||
if same:
|
||||
heading = next(h for k, h, _ in browse.GROUPS if k == lst.group)
|
||||
after += (f'<nav class="region-nav" aria-label="{esc(heading)}">{esc(heading)}: ' + " · ".join(
|
||||
f'<a href="{esc(browse.path(o))}">{esc(o.title)}</a> ({n})' for o, n in same) + "</nav>")
|
||||
after += placefacets.places_nav(lst, facet_plan)
|
||||
after += reference.terms_nav(path, repo_root)
|
||||
t, d, b, needs_map = regions.list_page(lst, recs, len(records), site, records=records, before=before, after=after)
|
||||
list_paths.append(path)
|
||||
add(path, t, d, b, maps=needs_map, recs=recs)
|
||||
t, d, b = regions.lists_index_page(records, site)
|
||||
t, d, b = regions.lists_index_page(records, site, extras)
|
||||
add("/lists/", t, d, b)
|
||||
t, d, b, needs_map = regions.routes_page(records, site, repo_root)
|
||||
t, d, b, needs_map = regions.routes_page(records, site, repo_root, after=reference.terms_nav("/routes/", repo_root),
|
||||
author_pages=({c: authors.credit_html(c, links) for c, links in author_links.items()}
|
||||
if authors_built else None))
|
||||
add("/routes/", t, d, b, maps=needs_map, recs=[r for r in records if facets.kind(r) == "route"])
|
||||
t, d, b = docs.sources_page(records, site, repo_root)
|
||||
add("/sources/", t, d, b)
|
||||
@@ -166,6 +267,6 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
if site.base_url: # its links are absolute
|
||||
with open(os.path.join(out_dir, "llms.txt"), "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(seo.llms_txt(records, site, changelog))
|
||||
seo.write_seo_files(out_dir, seo.all_paths(records, region_paths + ["/lists/"] + list_paths), site, dates)
|
||||
seo.write_seo_files(out_dir, seo.all_paths(records, region_paths + ["/lists/"] + list_paths, view_paths), site, dates)
|
||||
print(f"pages written {pages}: {len(records)} trail pages, home, 404, places, lists, about")
|
||||
return pages
|
||||
@@ -0,0 +1,118 @@
|
||||
"""A page for one kind of trail in one state or province: /regions/<place>/<list key>/.
|
||||
|
||||
For every place and every list that has a `noun` (olt/browse.py), the page exists when the place has at
|
||||
least MIN_SIZE trails in the list, no more than MAX_SHARE of the place's trails are in it (else it
|
||||
would repeat the place page), and its trails are not nearly the same set as another such page of
|
||||
the same place. A new trail or a corrected record moves pages in and out with no change here.
|
||||
"""
|
||||
from . import browse, common, facets, home, regions, summary
|
||||
from .markup import Markup, esc
|
||||
|
||||
SAME_SET = 0.8 # two pages of one place whose trails overlap by this share (of the smaller union) are one page
|
||||
|
||||
|
||||
def _jaccard(a, b):
|
||||
return len(a & b) / len(a | b)
|
||||
|
||||
|
||||
def plan(records):
|
||||
"""[{slug, info, lst, recs, path}] for every page, in place then list order."""
|
||||
shown = {lst.key for lst, _ in browse.shown(records)}
|
||||
by_slug, _ = regions.collect_regions(records)
|
||||
out = []
|
||||
for slug in sorted(by_slug):
|
||||
info = by_slug[slug]
|
||||
here = info["records"]
|
||||
kept = []
|
||||
for lst in browse.facet_lists():
|
||||
if lst.key not in shown:
|
||||
continue
|
||||
recs = browse.members(lst, here)
|
||||
if len(recs) < browse.MIN_SIZE or len(recs) > browse.MAX_SHARE * len(here):
|
||||
continue
|
||||
ids = {r["id"] for r in recs}
|
||||
if any(_jaccard(ids, other) >= SAME_SET for other in kept):
|
||||
continue
|
||||
kept.append(ids)
|
||||
out.append({"slug": slug, "info": info, "lst": lst, "recs": recs,
|
||||
"path": f"/regions/{slug}/{lst.key}/"})
|
||||
return out
|
||||
|
||||
|
||||
def label(lst):
|
||||
"""A short name for the page in a list of links."""
|
||||
return lst.title
|
||||
|
||||
|
||||
def pages_by_place(pages):
|
||||
"""slug -> [page], in plan order."""
|
||||
out = {}
|
||||
for p in pages:
|
||||
out.setdefault(p["slug"], []).append(p)
|
||||
return out
|
||||
|
||||
|
||||
def pages_by_list(pages):
|
||||
out = {}
|
||||
for p in pages:
|
||||
out.setdefault(p["lst"].key, []).append(p)
|
||||
return out
|
||||
|
||||
|
||||
def places_nav(lst, pages):
|
||||
"""HTML for a list's page: the places that have a page of their own for it."""
|
||||
here = pages_by_list(pages).get(lst.key, [])
|
||||
if not here:
|
||||
return ""
|
||||
links = " · ".join(f'<a href="{esc(p["path"])}">{esc(p["info"]["name"])}</a> ({len(p["recs"])})'
|
||||
for p in sorted(here, key=lambda p: p["info"]["name"]))
|
||||
return (f'<nav class="region-nav" aria-label="{esc(lst.title)} by place">'
|
||||
f'{esc(lst.title)} in a state or province, and how many there: {links}</nav>')
|
||||
|
||||
|
||||
def page(p, records, site, all_pages):
|
||||
"""(title, description, body, needs_map) for one place-and-list page."""
|
||||
lst, info, recs = p["lst"], p["info"], p["recs"]
|
||||
here = info["records"]
|
||||
name = info["name"]
|
||||
only_routes = all(facets.kind(r) == "route" for r in recs)
|
||||
count = f"{len(recs)} {'Routes' if only_routes else 'Trails'}"
|
||||
title = common.fit_title([f"{lst.noun} in {name}: {count}", f"{lst.noun} in {name}"], site)
|
||||
h1 = f"{lst.noun} in {name}"
|
||||
n_gpx = sum(1 for r in recs if facets.gpx_here(r))
|
||||
gpx = f", {n_gpx} with a GPX here" if n_gpx else ""
|
||||
lede = (f"{esc(lst.blurb)} {len(recs)} of the {len(here)} trails in {esc(name)}{gpx}. "
|
||||
f'<a href="{esc(facets.place_path(info["key"]))}">All the trails in {esc(name)}</a>.')
|
||||
siblings = [q for q in pages_by_place(all_pages)[p["slug"]] if q is not p]
|
||||
others = [q for q in pages_by_list(all_pages)[lst.key] if q is not p]
|
||||
nav = ""
|
||||
if siblings:
|
||||
nav += (f'<nav class="region-nav" aria-label="More in {esc(name)}">More in {esc(name)}: '
|
||||
+ " · ".join(f'<a href="{esc(q["path"])}">{esc(q["lst"].title)}</a> ({len(q["recs"])})' for q in siblings)
|
||||
+ "</nav>")
|
||||
if others:
|
||||
nav += (f'<nav class="region-nav" aria-label="{esc(lst.title)} elsewhere">{esc(lst.title)} elsewhere: '
|
||||
+ " · ".join(f'<a href="{esc(q["path"])}">{esc(q["info"]["name"])}</a> ({len(q["recs"])})'
|
||||
for q in sorted(others, key=lambda q: q["info"]["name"])) + "</nav>")
|
||||
crumbs = (f'<li><a href="/">Trails</a></li><li><a href="/regions/">Places</a></li>'
|
||||
f'<li><a href="{esc(facets.place_path(info["key"]))}">{esc(name)}</a></li>')
|
||||
body = f"""<div class="page-head"><div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{crumbs}<li aria-current="page">{esc(lst.title)}</li></ol></nav>
|
||||
<header class="titleblock"><div class="titleblock__text">
|
||||
<p class="kicker">{esc(name)}</p>
|
||||
<h1>{esc(h1)}</h1>
|
||||
<p class="page-head__lede">{lede}</p>
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
<div class="prose place-summary">{summary.facts(recs, records)}</div>
|
||||
{home.overview_map(recs, f"Map of the trails in {name}: {lst.title}")}
|
||||
{home.results(recs, default_sort=lst.sort, top=2)}
|
||||
<nav class="region-nav" aria-label="Lists"><a href="{esc(browse.path(lst))}">{esc(lst.title)} everywhere</a> · <a href="/lists/">All lists</a></nav>
|
||||
{nav}
|
||||
</div>"""
|
||||
by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"]))
|
||||
first = (f"{count} in {name}, from {common.plain_name(by_length[0])}, {regions._miles(by_length[0])} miles, "
|
||||
f"to {common.plain_name(by_length[-1])}, {regions._miles(by_length[-1])} miles.")
|
||||
desc = regions._fit([f"{lst.blurb} {first}", f"{lst.noun} in {name}: {first}"])
|
||||
return title, desc, Markup(body), home.has_overview_map(recs)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Two reference pages: the Glossary (/glossary/) and the Method (/method/).
|
||||
|
||||
The glossary is read from glossary.toml. The method page is generated from the definitions in
|
||||
docs/schema.md and from the records: how many have each figure, and how the measured lengths of the
|
||||
tracks compare with the published ones.
|
||||
"""
|
||||
import collections
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
|
||||
from . import common, datafiles, elevation, facets, hike, pagekit, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
GLOSSARY = "/glossary/"
|
||||
METHOD = "/method/"
|
||||
|
||||
|
||||
# Glossary ---------------------------------------------------------------------------
|
||||
|
||||
def terms(repo_root):
|
||||
return datafiles.glossary(repo_root)
|
||||
|
||||
|
||||
def terms_for(path, repo_root):
|
||||
"""The glossary terms that point at a page: [(term id, term)]."""
|
||||
return [(t["id"], t["term"]) for t in terms(repo_root) if path in t.get("see", [])]
|
||||
|
||||
|
||||
def terms_nav(path, repo_root):
|
||||
"""A line of links to the glossary entries for a page, or ""."""
|
||||
found = terms_for(path, repo_root)
|
||||
if not found:
|
||||
return ""
|
||||
links = " · ".join(f'<a href="{GLOSSARY}#{esc(i)}">{esc(t)}</a>' for i, t in found)
|
||||
return f'<nav class="region-nav" aria-label="Terms used on this page">Terms used on this page: {links}</nav>'
|
||||
|
||||
|
||||
def glossary_page(repo_root, labels, site):
|
||||
"""(title, description, body, terms) for /glossary/. labels: {path: link text} for every page built,
|
||||
so that a term links only to a page that exists."""
|
||||
ts = terms(repo_root)
|
||||
if not ts:
|
||||
return None
|
||||
entries = ""
|
||||
for t in ts:
|
||||
see = [(p, labels[p]) for p in t.get("see", []) if p in labels]
|
||||
see_html = (" See: " + ", ".join(f'<a href="{esc(p)}">{esc(label)}</a>' for p, label in see) + ".") if see else ""
|
||||
src = (f' Source: <a href="{esc(t["source_url"])}">{esc(t["source_url"])}</a>.') if t.get("source_url") else ""
|
||||
entries += (f'<div class="gloss"><dt id="{esc(t["id"])}">{esc(t["term"])}</dt>'
|
||||
f'<dd>{esc(t["definition"])}{src}{see_html}</dd></div>\n')
|
||||
lede = (f"{len(ts)} words this site uses for long trails, as it uses them. Each entry says what the word means here, "
|
||||
f"and links to the list or page where it applies.")
|
||||
body = (pagekit.head("Glossary of long trail terms", lede, [("Trails", "/"), ("Lists", "/lists/")])
|
||||
+ f"""<div class="container section place">
|
||||
<dl class="prose glossary">{entries}</dl>
|
||||
<nav class="region-nav" aria-label="Related pages"><a href="{METHOD}">How lengths are measured</a> · <a href="/lists/">All lists</a> · <a href="/data/schema/">Record schema</a></nav>
|
||||
</div>""")
|
||||
title = common.fit_title([f"Hiking Trail Glossary: {len(ts)} Terms Used Here", "Hiking Trail Glossary"], site)
|
||||
names = words.join_names(t["term"] for t in ts[:5])
|
||||
desc = common.cut_at_word(f"{len(ts)} long trail terms as this site uses them, from {names} "
|
||||
f"to {ts[-1]['term'].lower()}, each linked to where it applies.", common.DESCRIPTION_LIMIT)
|
||||
return title, desc, Markup(body), ts
|
||||
|
||||
|
||||
# Method -----------------------------------------------------------------------------
|
||||
|
||||
def schema_meanings(repo_root):
|
||||
"""{field: meaning} from the tables of docs/schema.md, with the code marks removed. A field in two
|
||||
tables keeps its first meaning."""
|
||||
out = {}
|
||||
for base in (repo_root, datafiles.REAL_ROOT):
|
||||
path = os.path.join(base or datafiles.REAL_ROOT, "docs", "schema.md")
|
||||
if os.path.isfile(path):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
m = re.match(r"\|\s*`([a-z_.]+)`[^|]*\|[^|]*\|\s*(.*?)\s*\|[^|]*\|?\s*$", line)
|
||||
if m and m.group(1) not in out:
|
||||
out[m.group(1)] = re.sub(r"`", "", m.group(2))
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _sentence(text):
|
||||
return common.sentence(text.strip())
|
||||
|
||||
|
||||
def verified(records):
|
||||
"""[(record, difference percent)] for the records whose track was measured."""
|
||||
out = []
|
||||
for r in records:
|
||||
v = r.get("verification", {})
|
||||
d = v.get("difference_percent")
|
||||
if v.get("verified") and isinstance(d, (int, float)) and not isinstance(d, bool):
|
||||
out.append((r, d))
|
||||
return out
|
||||
|
||||
|
||||
def method_page(records, site, repo_root):
|
||||
"""(title, description, body) for /method/."""
|
||||
meaning = schema_meanings(repo_root)
|
||||
ver = verified(records)
|
||||
n = len(records)
|
||||
within = lambda lo, hi: sum(1 for _, d in ver if lo <= abs(d) < hi) # noqa: E731
|
||||
limit = common.LENGTH_LIMIT
|
||||
bands = [("Within 5 percent", within(0, 5)), ("5 to 15 percent", within(5, limit)),
|
||||
(f"More than {limit:.0f} percent", sum(1 for _, d in ver if abs(d) >= limit))]
|
||||
gaps = sum(1 for r, _ in ver if r.get("source", {}).get("length_gap_note"))
|
||||
mid = statistics.median(abs(d) for _, d in ver) if ver else 0
|
||||
no_track = sum(1 for r in records if not common.has_line(r))
|
||||
elev = [(r, elevation.get(r)) for r in records if elevation.get(r)]
|
||||
src = collections.Counter((e["source"].get("model", ""), e["source"].get("smoothing", ""),
|
||||
e["source"].get("sample_spacing_m")) for _, e in elev if e.get("source"))
|
||||
model, smoothing, spacing = src.most_common(1)[0][0] if src else ("", "", None)
|
||||
limits = collections.Counter(e["source"]["limits"] for _, e in elev if e.get("source", {}).get("limits"))
|
||||
limits_text = limits.most_common(1)[0][0] if limits else ""
|
||||
stated = sum(1 for r in records if not facets.time_days(r)[2])
|
||||
(a, b), (c, d_) = facets.PACE_KM, facets.PACE_KM_CROSS
|
||||
coverage = []
|
||||
for label, fn in (("A usual time stated by a source", lambda r: not facets.time_days(r)[2]),
|
||||
("A season", lambda r: bool(facets.months(r))), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
|
||||
("Terrain", lambda r: bool(facets.terrain(r))), ("What the walking is", lambda r: bool(facets.walking(r))),
|
||||
("A computed climb that covers the whole trail", lambda r: facets.row_climb_m(r) is not None),
|
||||
("A track included here", common.has_line)):
|
||||
have = sum(1 for r in records if fn(r))
|
||||
coverage.append([label, str(have), str(n - have)])
|
||||
rows = [[label, str(k), f"{k / len(ver) * 100:.0f}%" if ver else ""] for label, k in bands]
|
||||
body = (pagekit.head("How the figures are measured", (
|
||||
f"What each figure on this site means, and how far to trust it. {len(ver)} of the {n} trails have a track whose "
|
||||
f"length was measured and checked against the published length."), [("Trails", "/"), ("About", "/about/")])
|
||||
+ f"""<div class="container section place"><div class="prose">
|
||||
<h2>Length</h2>
|
||||
<p>{esc(_sentence(meaning.get("length_km", "")))} It is the figure the trail’s holder or author gives, and each record says where it comes from. The lists and pages show it in miles with kilometres after.</p>
|
||||
<p>Where a track is included, its length is measured along the track as a geodesic length and compared with the published figure. The difference is the measured length minus the published length, as a percent of the published length. Track ends within 100 metres are joined, and the number of parts left is shown.</p>
|
||||
<p>Across the {len(ver)} measured tracks, the middle difference is {mid:.1f} percent.</p>
|
||||
{pagekit.table(["Measured against published", "Tracks", "Share"], rows, caption="How the measured tracks compare", numeric=(1, 2))}
|
||||
<p>A track that differs by more than {limit:.0f} percent needs a reason in its record, such as a trail that is partly unbuilt, a published length that is a planned one, or side trails counted in the figure. {gaps} of the {len(ver)} measured tracks give one. A track that covers only part of a trail is marked as partial, and its measured length is not its trail’s length.</p>
|
||||
<p>{no_track} records have no track included. Their length is the published figure alone, and nothing has been measured.</p>
|
||||
<h2>Time</h2>
|
||||
<p>{esc(_sentence(meaning.get("days", "").replace(" [fewest, most],", "")))} {stated} of the {n} records have a time a source states. For the others the page estimates it from the length, at {round(words.km_to_mi(a))} to {round(words.km_to_mi(b))} miles ({a} to {b} km) a day, or {round(words.km_to_mi(c))} to {round(words.km_to_mi(d_))} miles ({c} to {d_} km) a day where much of the trail is cross-country. An estimate is labelled as one wherever it is shown.</p>
|
||||
<h2>Climb</h2>
|
||||
<p>Climb is the total ascent along the track.{(" It uses " + esc(model) + ", sampled every " + words.fmt_int(spacing) + " metres, with " + esc(smoothing[:1].lower() + smoothing[1:]) + ".") if model and spacing else ""} {esc(limits_text)}</p>
|
||||
<p>A climb is ranked or shown in a list only where its track covers the whole trail: a track that covers part of the trail, or more than the trail, would mislead.</p>
|
||||
<h2>Season and high point</h2>
|
||||
<p>{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} Not every record has them, so a page built from them says how many records it covers.</p>
|
||||
<h2>What the records have</h2>
|
||||
{pagekit.table(["Figure", "Records with it", "Records without"], coverage, caption="How many records carry each figure", numeric=(1, 2))}
|
||||
<p>Every fact is read on a page that the record names. See the <a href="/sources/">sources</a>, the <a href="/data/schema/">record schema</a> and <a href="{GLOSSARY}">the glossary</a>.</p>
|
||||
</div>
|
||||
<nav class="region-nav" aria-label="Related pages"><a href="/numbers/">Trails by the numbers</a> · <a href="/lists/">All lists</a></nav></div>""")
|
||||
title = "How Trail Lengths and Climbs Are Measured"
|
||||
desc = common.cut_at_word(f"How this site checks published trail lengths against measured tracks, estimates time and computes climb, "
|
||||
f"with how many of the {n} records carry each figure.", common.DESCRIPTION_LIMIT)
|
||||
return title, desc, Markup(body)
|
||||
+85
-30
@@ -6,7 +6,7 @@ The section is called Places; its pages keep their /regions/ URLs.
|
||||
"""
|
||||
import collections
|
||||
|
||||
from . import browse, common, facets, home, words
|
||||
from . import browse, common, facets, home, summary, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
|
||||
@@ -116,8 +116,31 @@ def regions_index_page(records, site):
|
||||
return "Long Trails by State and Province: US and Canada", common.cut_at_word(description, common.DESCRIPTION_LIMIT), Markup(body)
|
||||
|
||||
|
||||
def region_page(slug, records, site):
|
||||
"""(title, description, body, needs_map) for /regions/<slug>/: the trails in one state or province."""
|
||||
def place_note(info, by_slug, records):
|
||||
"""A paragraph (HTML) on how the place stands among the others: its share of the trails, and which place
|
||||
in its part of the country has the most."""
|
||||
n, total = len(info["records"]), len(records)
|
||||
parts = [f"{esc(info['name'])} has {_plural(n, 'trail')} of the {total} trails on this site, "
|
||||
f"{n / total * 100:.1f} percent of them."]
|
||||
group = info["group"]
|
||||
if group:
|
||||
mates = [i for i in by_slug.values() if i["group"] == group]
|
||||
top = max(mates, key=lambda i: (len(i["records"]), i["name"]))
|
||||
gname = facets.GROUP_NAME[group]
|
||||
if len(mates) > 1:
|
||||
if top is info:
|
||||
parts.append(f"Of the {len(mates)} places in {esc(gname)} with trails here, it has the most.")
|
||||
else:
|
||||
parts.append(f"Of the {len(mates)} places in {esc(gname)} with trails here, "
|
||||
f'<a href="{esc(facets.place_path(top["key"]))}">{esc(top["name"])}</a> has the most, '
|
||||
f"{len(top['records'])}.")
|
||||
return Markup("<p>" + " ".join(parts) + "</p>")
|
||||
|
||||
|
||||
def region_page(slug, records, site, facet_pages=()):
|
||||
"""(title, description, body, needs_map) for /regions/<slug>/: the trails in one state or province.
|
||||
|
||||
facet_pages: [(label, path, how many)] for this place's pages of one kind of trail (olt/placefacets.py)."""
|
||||
by_slug, _ = collect_regions(records)
|
||||
info = by_slug[slug]
|
||||
recs = info["records"]
|
||||
@@ -140,6 +163,11 @@ def region_page(slug, records, site):
|
||||
held = lists_here(recs, records)
|
||||
nav += (f'<nav class="region-nav" aria-label="Lists with trails in {esc(info["name"])}">'
|
||||
f'Lists with trails in {esc(info["name"])}, and how many here: {" · ".join(held)}</nav>') if held else ""
|
||||
if facet_pages:
|
||||
nav += (f'<nav class="region-nav" aria-label="Kinds of trail in {esc(info["name"])}">'
|
||||
f'More in {esc(info["name"])}: '
|
||||
+ " · ".join(f'<a href="{esc(path)}">{esc(label)}</a> ({n})' for label, path, n in facet_pages) + "</nav>")
|
||||
standing_note = place_note(info, by_slug, records)
|
||||
body = f"""<div class="page-head"><div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{crumbs}<li aria-current="page">{esc(info["name"])}</li></ol></nav>
|
||||
<header class="titleblock"><div class="titleblock__text">
|
||||
@@ -150,6 +178,7 @@ def region_page(slug, records, site):
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
<div class="prose place-summary">{summary.facts(recs, records)}{standing_note}{summary.details(recs)}</div>
|
||||
{home.overview_map(recs, f"Map of the trails in {info['name']}")}
|
||||
{home.results(recs, top=2)}
|
||||
{nav}
|
||||
@@ -196,13 +225,15 @@ def route_guides(rec):
|
||||
f'<ul class="route-guides">{items}</ul></div>')
|
||||
|
||||
|
||||
def routes_page(records, site, repo_root=None):
|
||||
def routes_page(records, site, repo_root=None, after="", author_pages=None):
|
||||
"""(title, description, body, needs_map) for /routes/: the Routes list."""
|
||||
routes = [r for r in records if facets.kind(r) == "route"]
|
||||
by_author = collections.defaultdict(list)
|
||||
for r in routes:
|
||||
by_author[facets.author(r) or "Author not named"].append(r)
|
||||
groups = [(f"By {esc(a)}", sorted(by_author[a], key=home.sort_name), route_guides)
|
||||
linked = author_pages is not None
|
||||
author_pages = author_pages or {}
|
||||
groups = [(f"By {author_pages[a]}" if a in author_pages else f"By {esc(a)}", sorted(by_author[a], key=home.sort_name), route_guides)
|
||||
for a in sorted(by_author, key=str.lower)]
|
||||
n_gpx = _gpx_count(routes)
|
||||
body = f"""<div class="page-head"><div class="container">
|
||||
@@ -224,7 +255,8 @@ def routes_page(records, site, repo_root=None):
|
||||
<div class="container section">
|
||||
{home.overview_map(routes, "Map of the routes with a GPX here")}
|
||||
{home.results(groups=groups, routes_list=True, top=2)}
|
||||
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
|
||||
{after}
|
||||
<nav class="region-nav" aria-label="Other lists">{'<a href="/authors/">Route authors</a> · ' if linked else ""}<a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
|
||||
</div>"""
|
||||
description = (f"{_plural(len(routes), 'route')} in the United States and Canada by {len(by_author)} authors, "
|
||||
f"with their guides{f' and {n_gpx} with a GPX here' if n_gpx else ''}.")
|
||||
@@ -232,24 +264,33 @@ def routes_page(records, site, repo_root=None):
|
||||
Markup(body), home.has_overview_map(routes))
|
||||
|
||||
|
||||
def list_page(lst, recs, total, site):
|
||||
"""(title, description, body, needs_map) for /lists/<key>/."""
|
||||
def list_page(lst, recs, total, site, *, records=None, before="", after=""):
|
||||
"""(title, description, body, needs_map) for /lists/<key>/.
|
||||
|
||||
records: every trail, for the summary and the note. before: HTML placed above the map (a table
|
||||
of figures); after: HTML placed under the list (links to related lists, places and terms)."""
|
||||
n_gpx = _gpx_count(recs)
|
||||
rule = (f"Lists are picked out by rule from each trail’s facts, so they change as trails are added "
|
||||
f"or corrected. A list is shown when it has at least {browse.MIN_SIZE} trails and no more than "
|
||||
f"{round(browse.MAX_SHARE * 100)}% of the {total}.")
|
||||
note = lst.note(recs, records) if lst.note and records is not None else ""
|
||||
note = f" {esc(note)}" if note else ""
|
||||
about = summary.facts(recs, records) if records is not None else ""
|
||||
body = f"""<div class="page-head"><div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/">Trails</a></li>
|
||||
<li><a href="/lists/">Lists</a></li><li aria-current="page">{esc(lst.title)}</li></ol></nav>
|
||||
<header class="titleblock"><div class="titleblock__text">
|
||||
<p class="kicker">A list</p>
|
||||
<h1>{esc(lst.title)}</h1>
|
||||
<p class="page-head__lede">{esc(lst.blurb)} {_plural(len(recs))}, {n_gpx} with a GPX here.</p>
|
||||
<p class="page-head__lede">{esc(lst.blurb)} {_plural(len(recs))}, {n_gpx} with a GPX here.{note}</p>
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section">
|
||||
<div class="container section place">
|
||||
<div class="prose place-summary">{about}</div>
|
||||
{before}
|
||||
{home.overview_map(recs, f"Map of the trails in the list {lst.title}")}
|
||||
{home.results(recs, default_sort=lst.sort, top=2)}
|
||||
{after}
|
||||
<p class="finder__foot">{rule}</p>
|
||||
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
|
||||
</div>"""
|
||||
@@ -261,30 +302,44 @@ def list_page(lst, recs, total, site):
|
||||
return lst.search_title(len(recs)), desc, Markup(body), home.has_overview_map(recs)
|
||||
|
||||
|
||||
def lists_index_page(records, site):
|
||||
"""(title, description, body) for /lists/: every list shown today, with a few of its trails."""
|
||||
cards = []
|
||||
for lst, recs in browse.shown(records):
|
||||
sample = "".join(
|
||||
f'<li><a href="{esc(common.trail_path(r))}">{common.name(r)}</a> '
|
||||
f'<span class="shelf__len">{words.length(r["length_km"], "short", r["derived"]["length_mi"])}</span></li>'
|
||||
for r in recs[:4])
|
||||
cards.append(f"""<li class="shelf">
|
||||
<h2 class="shelf__title"><a href="{esc(browse.path(lst))}">{esc(lst.title)}</a> <span class="shelf__count">{len(recs)}</span></h2>
|
||||
<p class="shelf__blurb">{esc(lst.blurb)}</p>
|
||||
<ul class="shelf__items">{sample}</ul>
|
||||
<p class="shelf__more"><a href="{esc(browse.path(lst))}">See all {len(recs)}<span class="vh">: {esc(lst.title)}</span></a></p>
|
||||
</li>""")
|
||||
def lists_index_page(records, site, extras=()):
|
||||
"""(title, description, body) for /lists/: every list shown today, under its heading, and the
|
||||
other ways in (tables, authors, reference pages) that pages.py hands over as extras.
|
||||
|
||||
extras: [(group key, title, blurb, path, how many)] for pages that are not lists."""
|
||||
shown = browse.shown(records)
|
||||
sections = ""
|
||||
for key, heading, intro in browse.GROUPS + EXTRA_GROUPS:
|
||||
items = [(lst.title, lst.blurb, browse.path(lst), len(recs)) for lst, recs in shown if lst.group == key]
|
||||
items += [(t, b, path, n) for g, t, b, path, n in extras if g == key]
|
||||
if not items:
|
||||
continue
|
||||
cards = "".join(f"""<li class="shelf">
|
||||
<h3 class="shelf__title"><a href="{esc(path)}">{esc(title)}</a>{f' <span class="shelf__count">{n}</span>' if n else ""}</h3>
|
||||
<p class="shelf__blurb">{esc(blurb)}</p>
|
||||
</li>""" for title, blurb, path, n in items)
|
||||
sections += f"""<section class="lists-group" aria-labelledby="group-{esc(key)}">
|
||||
<h2 id="group-{esc(key)}">{esc(heading)}</h2>
|
||||
<p class="places__sum">{esc(intro)}</p>
|
||||
<ul class="shelves">{cards}</ul>
|
||||
</section>"""
|
||||
body = f"""<div class="page-head"><div class="container">
|
||||
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/">Trails</a></li><li aria-current="page">Lists</li></ol></nav>
|
||||
<header class="titleblock"><div class="titleblock__text"><h1>Lists</h1>
|
||||
<p class="page-head__lede">Ready-made selections of the {len(records)} trails, a way to start. Each is
|
||||
picked out by rule from what each trail’s page says, so a list grows as trails are added.</p>
|
||||
<p class="page-head__lede">Ready-made selections of the {len(records)} trails, and the tables and reference pages
|
||||
built from them. Each list is picked out by rule from what each trail’s page says, so it grows as trails are added.</p>
|
||||
</div></header></div></div>
|
||||
<div class="container section"><ul class="shelves">{"".join(cards)}</ul>
|
||||
<div class="container section place">{sections}
|
||||
<p class="finder__foot">A list is shown when it has at least {browse.MIN_SIZE} trails and no more than
|
||||
{round(browse.MAX_SHARE * 100)}% of all of them. To combine conditions, use the filters on <a href="/">the home page</a>.</p></div>"""
|
||||
shown = browse.shown(records)
|
||||
desc = (f"{len(shown)} ready-made lists of the {len(records)} long trails, each picked out by rule from the records: "
|
||||
f"by length, time, terrain, type and country.")
|
||||
return "Long Hiking Trail Lists: Length, Terrain and Type", common.cut_at_word(desc, common.DESCRIPTION_LIMIT), Markup(body)
|
||||
f"by length, time to walk, month, terrain, who looks after it and type, with tables and a glossary.")
|
||||
return "Long Hiking Trail Lists: Length, Time and Terrain", common.cut_at_word(desc, common.DESCRIPTION_LIMIT), Markup(body)
|
||||
|
||||
|
||||
# Headings for the pages that are not lists, after the lists' own (olt/browse.py GROUPS).
|
||||
EXTRA_GROUPS = (
|
||||
("tables", "Tables and rankings", "The trails laid side by side and ranked, with the caveats that go with each figure."),
|
||||
("changes", "What is new", "The newest trails and the newest changes to them."),
|
||||
("reference", "Reference", "What the words mean, and how the figures are measured."),
|
||||
)
|
||||
+49
-8
@@ -84,6 +84,15 @@ def modified(rec):
|
||||
return max(record_dates(rec), default="")
|
||||
|
||||
|
||||
def checked(rec):
|
||||
"""The newest date the record itself was checked on: its verification, its [hike] facts or its
|
||||
source read. This is the date a trail page shows as "Last checked" and the page's
|
||||
dateModified. A history entry is a change or a request, not a check, so it is left out."""
|
||||
found = [rec.get("verification", {}).get("date"), hike.table(rec).get("checked"),
|
||||
rec.get("source", {}).get("source_checked")]
|
||||
return max((str(d) for d in found if d and re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(d))), default="")
|
||||
|
||||
|
||||
def newest(recs):
|
||||
"""The newest modified() among records: the date of a page that lists them."""
|
||||
return max((modified(r) for r in recs), default="")
|
||||
@@ -334,7 +343,7 @@ def trail_jsonld(rec, site, *, title, description):
|
||||
"""The nodes for one trail page: its ItemPage and its Place. layout.layout adds the breadcrumb."""
|
||||
path = f"/trails/{rec['id']}/"
|
||||
place = place_node(rec, site)
|
||||
return [page_node("ItemPage", path, site, name=title, description=description, date=modified(rec),
|
||||
return [page_node("ItemPage", path, site, name=title, description=description, date=checked(rec),
|
||||
main={"@id": place["@id"]}, breadcrumb_id=breadcrumb_id(site, path)), place]
|
||||
|
||||
|
||||
@@ -348,13 +357,43 @@ def collection_jsonld(path, site, *, title, description, recs, date=""):
|
||||
breadcrumb_id=breadcrumb_id(site, path))]
|
||||
|
||||
|
||||
def glossary_jsonld(path, site, *, title, description, terms, date=""):
|
||||
"""The glossary page: a WebPage whose main entity is a DefinedTermSet of the terms it defines."""
|
||||
items = [{"@type": "DefinedTerm", "name": t["term"], "description": t["definition"],
|
||||
"url": url_of(site, path) + "#" + t["id"], "inDefinedTermSet": {"@id": url_of(site, path) + "#terms"}}
|
||||
for t in terms]
|
||||
main = {"@type": "DefinedTermSet", "@id": url_of(site, path) + "#terms", "name": title, "hasDefinedTerm": items}
|
||||
return [page_node("WebPage", path, site, name=title, description=description, date=date, main=main,
|
||||
breadcrumb_id=breadcrumb_id(site, path))]
|
||||
|
||||
|
||||
def article_jsonld(path, site, *, title, description, date=""):
|
||||
"""A plain page of text and tables (the method page): a WebPage."""
|
||||
return [page_node("WebPage", path, site, name=title, description=description, date=date,
|
||||
breadcrumb_id=breadcrumb_id(site, path))]
|
||||
|
||||
|
||||
def person_node(site):
|
||||
"""The maintainer, as site.toml names them: a Person with their profile page as `sameAs`.
|
||||
{} when site.toml names no maintainer. Name and profile page only."""
|
||||
if not site.maintainer_name:
|
||||
return {}
|
||||
node = {"@type": "Person", "@id": url_of(site, "/") + "#maintainer", "name": site.maintainer_name}
|
||||
if site.maintainer_url:
|
||||
node["url"] = site.maintainer_url
|
||||
node["sameAs"] = [site.maintainer_url]
|
||||
return _clean(node)
|
||||
|
||||
|
||||
def organization_node(site):
|
||||
"""The publisher: name, address, logo, and the repository and contact site.toml holds."""
|
||||
"""The publisher: name, address, logo, the repository and contact site.toml holds, and
|
||||
the maintainer as its founder (schema.org's property for the person behind a small organisation)."""
|
||||
node = {"@type": "Organization", "@id": url_of(site, "/") + "#organization", "name": site.name,
|
||||
"url": url_of(site, "/"), "description": site.tagline,
|
||||
"logo": url_of(site, "/assets/apple-touch-icon.png"),
|
||||
"sameAs": [site.repo_url] if site.repo_url else []}
|
||||
contact = site.contact_url
|
||||
"sameAs": [site.repo_url] if site.repo_url else [],
|
||||
"founder": person_node(site)}
|
||||
contact = site.contact
|
||||
if contact.startswith("mailto:"):
|
||||
node["email"] = contact[len("mailto:"):]
|
||||
elif contact:
|
||||
@@ -405,7 +444,8 @@ def dataset_jsonld(records, site, *, version=""):
|
||||
"isAccessibleForFree": True,
|
||||
"keywords": ["long-distance hiking trails", "hiking", "backpacking", "thru-hiking", "GPX", "GeoJSON",
|
||||
"trail length", "open data"] + countries,
|
||||
"creator": publisher,
|
||||
"creator": person_node(site) or publisher,
|
||||
"maintainer": person_node(site),
|
||||
"publisher": publisher,
|
||||
"sameAs": site.repo_url,
|
||||
"spatialCoverage": spatial,
|
||||
@@ -496,10 +536,11 @@ def write_seo_files(out_dir, paths, site, lastmod=None):
|
||||
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."""
|
||||
def all_paths(records, region_paths, extra_paths=()):
|
||||
"""Every indexable page path, in nav order then record pages. extra_paths: the view pages
|
||||
(tables, authors, glossary and the rest) that pages.render_site builds."""
|
||||
paths = ["/", "/regions/"] + list(region_paths) + [
|
||||
"/routes/", "/sources/", "/logos/", "/about/", "/data/",
|
||||
"/data/schema/", "/data/changelog/", "/left-out/"]
|
||||
"/data/schema/", "/data/changelog/", "/left-out/"] + list(extra_paths)
|
||||
paths += [common.trail_path(r) for r in sorted(records, key=lambda r: r["id"])]
|
||||
return paths
|
||||
+19
-2
@@ -12,7 +12,7 @@ class Site:
|
||||
"""The settings every page needs. Build one with load()."""
|
||||
|
||||
def __init__(self, name, tagline, base_url="", repo_url="", repo_branch="main",
|
||||
contact_url="", name_lang=None, home_title=""):
|
||||
contact_url="", name_lang=None, home_title="", maintainer_name="", maintainer_url=""):
|
||||
if not name:
|
||||
raise ValueError("site.toml: name must not be empty")
|
||||
self.name = name
|
||||
@@ -23,6 +23,10 @@ class Site:
|
||||
self.repo_url = repo_url.rstrip("/")
|
||||
self.repo_branch = (repo_branch or "main").strip() or "main"
|
||||
self.contact_url = contact_url.strip()
|
||||
# Who maintains the site, and the page about them: shown on the About page and
|
||||
# named in the structured data. Both are public by the owner's choice.
|
||||
self.maintainer_name = maintainer_name.strip()
|
||||
self.maintainer_url = maintainer_url.strip()
|
||||
# record id -> language tag of its name ("fr"), for names that are not English
|
||||
self.name_lang = dict(name_lang or {})
|
||||
|
||||
@@ -35,6 +39,18 @@ class Site:
|
||||
"""Where to report an error, or "" when repo_url is unset."""
|
||||
return self.repo_url + "/issues" if self.repo_url else ""
|
||||
|
||||
@property
|
||||
def issue_chooser_url(self):
|
||||
"""The repository's issue chooser (its forms and a blank issue), or "" when repo_url
|
||||
is not a GitHub repository."""
|
||||
return self.repo_url + "/issues/new/choose" if self.repo_url and self.is_github else ""
|
||||
|
||||
@property
|
||||
def contact(self):
|
||||
"""Where to write to the maintainers: contact_url, else the issue chooser, else "".
|
||||
No email address is ever built here; a mailto: contact_url is the owner's own choice."""
|
||||
return self.contact_url or self.issue_chooser_url
|
||||
|
||||
@property
|
||||
def is_github(self):
|
||||
"""True when repo_url is a github.com repository (the only host whose
|
||||
@@ -106,7 +122,8 @@ def from_file(path):
|
||||
base_url=data.get("base_url", ""), repo_url=data.get("repo_url", ""),
|
||||
repo_branch=data.get("repo_branch", "main"),
|
||||
contact_url=data.get("contact_url", ""), name_lang=data.get("name_lang", {}),
|
||||
home_title=data.get("home_title", ""))
|
||||
home_title=data.get("home_title", ""),
|
||||
maintainer_name=data.get("maintainer_name", ""), maintainer_url=data.get("maintainer_url", ""))
|
||||
|
||||
|
||||
@functools.cache
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""Tables built from the records: key figures for a set of trails, a collection set side by side
|
||||
(the Triple Crown), and the rankings under /numbers/.
|
||||
|
||||
Nothing here names a trail. A collection is read from collections.toml; a ranking takes the
|
||||
records that carry the figure and says how many that is. Every figure comes from a record field,
|
||||
and the climb and the high point carry the caveats the records themselves state.
|
||||
"""
|
||||
import collections
|
||||
import statistics
|
||||
|
||||
from . import browse, common, datafiles, elevation, facets, hike, pagekit, regions, seo, summary, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
NUMBERS = "/numbers/"
|
||||
RANKING_ROWS = 25 # rows in a ranking table (the page says how many records have the figure)
|
||||
HUB_ROWS = 10
|
||||
|
||||
|
||||
def _places(rec):
|
||||
return ", ".join(words.region_name(c) for c in rec.get("regions", []))
|
||||
|
||||
|
||||
def high_point(rec):
|
||||
"""(name, metres) as the record states them; either may be missing."""
|
||||
h = hike.table(rec)
|
||||
m = h.get("high_point_m")
|
||||
return h.get("high_point", ""), (m if isinstance(m, (int, float)) and not isinstance(m, bool) else None)
|
||||
|
||||
|
||||
def high_point_cell(rec):
|
||||
name, m = high_point(rec)
|
||||
if m is None and not name:
|
||||
return "Not on file"
|
||||
if m is None:
|
||||
return name
|
||||
return Markup(f"{esc(name + ', ') if name else ''}{words.elevation(m)}")
|
||||
|
||||
|
||||
def climb_cell(rec):
|
||||
m = facets.row_climb_m(rec)
|
||||
return "Not computed" if m is None else words.elevation(m)
|
||||
|
||||
|
||||
def time_cell(rec):
|
||||
return facets.time_text(rec)
|
||||
|
||||
|
||||
def season_cell(rec):
|
||||
return facets.season_text(rec) or "Not on file"
|
||||
|
||||
|
||||
# One figure: (label, function of a record). The order is the order of columns and rows.
|
||||
FIGURES = (
|
||||
("Length", lambda r: words.length(r["length_km"], mi=r["derived"]["length_mi"])),
|
||||
("States and provinces", _places),
|
||||
("Typical time", time_cell),
|
||||
("High point", high_point_cell),
|
||||
("Climb", climb_cell),
|
||||
("Season", season_cell),
|
||||
("Publisher", lambda r: r.get("source", {}).get("publisher", "") or "Not on file"),
|
||||
)
|
||||
|
||||
|
||||
def key_figures_table(recs, caption="Key figures"):
|
||||
"""One row per trail: length, places, time, high point, climb, season and publisher."""
|
||||
rows = [[pagekit.trail_link(r)] + [fn(r) for _, fn in FIGURES] for r in recs]
|
||||
return pagekit.table(["Trail"] + [label for label, _ in FIGURES], rows, caption=caption, row_heads=True)
|
||||
|
||||
|
||||
def figures_note(recs):
|
||||
"""What the figures in key_figures_table mean, with the caveats the records state."""
|
||||
est = sum(1 for r in recs if facets.time_days(r)[2])
|
||||
parts = [f"Times that start with “About” are estimated from the length ({est} of these). "
|
||||
"Otherwise a source states the time.",
|
||||
climb_caveat(recs)]
|
||||
return " ".join(p for p in parts if p)
|
||||
|
||||
|
||||
def climb_caveat(recs):
|
||||
"""The caveat the elevation files give for their climb figures: the most common one among recs."""
|
||||
limits = collections.Counter(
|
||||
e["source"]["limits"] for e in (elevation.get(r) for r in recs) if e and e.get("source", {}).get("limits"))
|
||||
text = limits.most_common(1)[0][0] if limits else ""
|
||||
return ("Climb: " + text) if text else ""
|
||||
|
||||
|
||||
def figures_section(recs, intro=""):
|
||||
return (f'<div class="prose"><p>{intro}</p></div>' if intro else "") + str(key_figures_table(recs)) + \
|
||||
f'<p class="finder__foot">{esc(figures_note(recs))}</p>'
|
||||
|
||||
|
||||
# Collections ----------------------------------------------------------------------
|
||||
|
||||
def collection_members(collection, records):
|
||||
by_id = {r["id"]: r for r in records}
|
||||
return [by_id[i] for i in collection.get("members", []) if i in by_id]
|
||||
|
||||
|
||||
def collection_path(collection):
|
||||
return f"/{collection['id']}/"
|
||||
|
||||
|
||||
def collection_page(collection, records, site):
|
||||
"""(title, description, body, recs) for a collection set side by side, or None when a member is missing.
|
||||
|
||||
The members are set in the order collections.toml gives, with every figure in a row of its own. The
|
||||
page ranks and recommends nothing."""
|
||||
recs = collection_members(collection, records)
|
||||
if not recs or len(recs) != len(collection["members"]):
|
||||
return None
|
||||
name = collection["name"]
|
||||
abbrs = words.join_names(r.get("short_name") or common.plain_name(r) for r in recs)
|
||||
title = common.fit_title([f"{name} Trails Compared: {abbrs}", f"{name} Trails Compared"], site)
|
||||
total_mi = sum(r["derived"]["length_mi"] for r in recs)
|
||||
total_km = sum(r["length_km"] for r in recs)
|
||||
places = {c for r in recs for c in r.get("regions", [])}
|
||||
lede = (f"{esc(collection['definition'])} Here are the {len(recs)} trails side by side, in the order the "
|
||||
f"definition names them, from what each trail's page says. Their published lengths add up to {words.fmt_int(total_mi)} "
|
||||
f"miles ({words.fmt_int(total_km)} km), across {len(places)} states and provinces.")
|
||||
headers = ["Figure"] + [common.plain_name(r) for r in recs]
|
||||
rows = [[label] + [fn(r) for r in recs] for label, fn in FIGURES]
|
||||
rows.insert(0, ["Full name"] + [pagekit.trail_link(r) for r in recs])
|
||||
rows.append(["Designated"] + [common.designated_year(r) or "Not on file" for r in recs])
|
||||
source = (f'<p class="finder__foot">The award is described by {esc(collection.get("source_publisher", "its holder"))} at '
|
||||
f'<a href="{esc(collection["source_url"])}">{esc(collection["source_url"])}</a>. '
|
||||
f'{esc(figures_note(recs))} Lengths are the published figures. '
|
||||
f'See the <a href="/method/">method</a> for how they are checked.</p>')
|
||||
from . import home
|
||||
body = (pagekit.head(f"{name} trails compared", lede, [("Trails", "/"), ("Lists", "/lists/")])
|
||||
+ '<div class="container section place">'
|
||||
f'{pagekit.table(headers, rows, caption=f"The {name} trails side by side", row_heads=True)}'
|
||||
f'{source}'
|
||||
f'<div class="prose place-summary">{summary.facts(recs, records)}</div>'
|
||||
f'{home.results(recs, top=2)}'
|
||||
'<nav class="region-nav" aria-label="Related pages"><a href="/lists/national-scenic-trails/">National Scenic Trails</a> · '
|
||||
f'<a href="/glossary/#{esc(collection["id"])}">What the {esc(name)} is</a> · <a href="/lists/">All lists</a></nav></div>')
|
||||
desc = common.cut_at_word(
|
||||
f"{name} trails side by side: published length, states, typical time, high point, climb and season for "
|
||||
f"{abbrs}. Figures from each trail's page, not ranked.", common.DESCRIPTION_LIMIT)
|
||||
return title, desc, Markup(body), recs
|
||||
|
||||
|
||||
# Numbers ----------------------------------------------------------------------------
|
||||
|
||||
def _rank_rows(recs, value_of, cell_of, extra=None):
|
||||
rows = []
|
||||
for i, r in enumerate(recs, 1):
|
||||
row = [str(i), pagekit.trail_link(r), cell_of(r)]
|
||||
if extra:
|
||||
row.append(extra(r))
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def _climb(rec):
|
||||
return facets.row_climb_m(rec)
|
||||
|
||||
|
||||
def _climb_rate(rec):
|
||||
c = _climb(rec)
|
||||
return None if c is None else c / rec["length_km"]
|
||||
|
||||
|
||||
# key, path tail, title head, table heading, test value
|
||||
RANKINGS = (
|
||||
("highest-points", "Hiking Trails Ranked by High Point",
|
||||
lambda r: high_point(r)[1], "High point",
|
||||
"ranked by the highest point a source states",
|
||||
lambda r: high_point_cell(r)),
|
||||
("most-climbing", "Hiking Trails Ranked by Climbing",
|
||||
_climb, "Climb",
|
||||
"ranked by total climbing along the track",
|
||||
lambda r: climb_cell(r)),
|
||||
("climb-per-mile", "Hiking Trails Ranked by Climb per Mile",
|
||||
_climb_rate, "Climb per mile",
|
||||
"ranked by total climbing for each mile of the trail",
|
||||
lambda r: pagekit.ft_per_mile(_climb_rate(r))),
|
||||
)
|
||||
|
||||
|
||||
def ranking_paths():
|
||||
return [f"{NUMBERS}{key}/" for key, *_ in RANKINGS]
|
||||
|
||||
|
||||
def _climb_coverage_note(records):
|
||||
withheld = sum(1 for r in records if elevation.get(r) and facets.row_climb_m(r) is None)
|
||||
have = sum(1 for r in records if facets.row_climb_m(r) is not None)
|
||||
return (f"{have} of the {len(records)} trails have a climb that can be ranked: it comes from a track that covers the whole "
|
||||
f"trail. {withheld} more have a track that covers only part of the trail, or more than the trail, and are left out.")
|
||||
|
||||
|
||||
def ranking_page(spec, records, site):
|
||||
"""(title, description, body, recs) for one ranking, or None when fewer than MIN_SIZE records have the figure."""
|
||||
key, head, value_of, label, how, cell_of = spec
|
||||
have = [r for r in records if value_of(r) is not None]
|
||||
if len(have) < browse.MIN_SIZE:
|
||||
return None
|
||||
ranked = sorted(have, key=lambda r: (-value_of(r), r["id"]))
|
||||
shown = ranked[:RANKING_ROWS]
|
||||
title = common.fit_title([f"{head}: {len(have)} Trails", head], site)
|
||||
if key == "highest-points":
|
||||
caveat = (f"{len(have)} of the {len(records)} trails have a high point stated in metres, as a source gives it. The rest "
|
||||
"give none, so they are not ranked.")
|
||||
else:
|
||||
caveat = _climb_coverage_note(records) + " " + climb_caveat(have)
|
||||
rows = _rank_rows(shown, value_of, cell_of, extra=lambda r: words.length(r["length_km"], mi=r["derived"]["length_mi"]))
|
||||
lede = (f"The {len(have)} trails and routes that have the figure, {how}. "
|
||||
f"The table shows the first {len(shown)}. {esc(caveat)}")
|
||||
from . import home
|
||||
body = (pagekit.head(head, lede, [("Trails", "/"), ("Lists", "/lists/"), ("By the numbers", NUMBERS)])
|
||||
+ '<div class="container section place">'
|
||||
f'{pagekit.table(["#", "Trail", label, "Length"], rows, caption=head, numeric=(0,))}'
|
||||
f'<p class="finder__foot">Where two trails share a figure, they are in name order. '
|
||||
f'The same figures are on each trail’s page. See the <a href="/method/">method</a> for what the caveats mean.</p>'
|
||||
f'<div class="prose place-summary">{summary.facts(have, records)}</div>'
|
||||
f'{home.results(have, default_sort="climb-desc" if key != "highest-points" else "length-desc", top=2)}'
|
||||
f'<nav class="region-nav" aria-label="Related pages"><a href="{NUMBERS}">By the numbers</a> · '
|
||||
f'<a href="/lists/">All lists</a></nav></div>')
|
||||
desc = common.cut_at_word(f"{len(have)} long hiking trails {how}, with the caveats that go with the figure.",
|
||||
common.DESCRIPTION_LIMIT)
|
||||
return title, desc, Markup(body), have
|
||||
|
||||
|
||||
def numbers_page(records, site, ranked_pages):
|
||||
"""(title, description, body) for /numbers/: lengths, places and links to the rankings.
|
||||
|
||||
ranked_pages: [(path, heading, how many)] for the rankings that were built."""
|
||||
from . import home
|
||||
by_length = sorted(records, key=lambda r: (-r["length_km"], r["id"]))
|
||||
miles = [r["derived"]["length_mi"] for r in records]
|
||||
mid = statistics.median(miles)
|
||||
lede = (f"The {len(records)} trails by length, climb and place. The middle length is {words.fmt_int(mid)} miles "
|
||||
f"({words.fmt_int(mid * words.KM_PER_MI)} km). Lengths are the published figures; the other pages here rank "
|
||||
"figures that only some trails have, and say how many.")
|
||||
longest = by_length[:HUB_ROWS]
|
||||
shortest = list(reversed(by_length[-HUB_ROWS:]))
|
||||
|
||||
def length_rows(rs):
|
||||
return [[str(i), pagekit.trail_link(r), words.length(r["length_km"], mi=r["derived"]["length_mi"]), time_cell(r)]
|
||||
for i, r in enumerate(rs, 1)]
|
||||
by_slug, _ = regions.collect_regions(records)
|
||||
place_rows = []
|
||||
for slug in sorted(by_slug, key=lambda s: (-len(by_slug[s]["records"]), by_slug[s]["name"])):
|
||||
info = by_slug[slug]
|
||||
rs = info["records"]
|
||||
top = max(rs, key=lambda r: (r["length_km"], r["id"]))
|
||||
place_rows.append([Markup(f'<a href="{esc(facets.place_path(info["key"]))}">{esc(info["name"])}</a>'),
|
||||
str(len(rs)), str(sum(1 for r in rs if facets.kind(r) == "route")),
|
||||
str(sum(1 for r in rs if facets.shape(r) == "loop")),
|
||||
str(sum(1 for r in rs if facets.gpx_here(r))),
|
||||
Markup(f'{pagekit.trail_link(top)}, {words.length(top["length_km"], mi=top["derived"]["length_mi"])}')])
|
||||
links = "".join(f'<li><a href="{esc(path)}">{esc(head)}</a> ({n} trails)</li>' for path, head, n in ranked_pages)
|
||||
body = (pagekit.head("Long trails by the numbers", lede, [("Trails", "/"), ("Lists", "/lists/")])
|
||||
+ f"""<div class="container section place">
|
||||
<section><h2>Rankings</h2><ul>{links}</ul></section>
|
||||
<section><h2>The {HUB_ROWS} longest by published length</h2>
|
||||
{pagekit.table(["#", "Trail", "Length", "Typical time"], length_rows(longest), caption="The longest trails", numeric=(0,))}</section>
|
||||
<section><h2>The {HUB_ROWS} shortest by published length</h2>
|
||||
{pagekit.table(["#", "Trail", "Length", "Typical time"], length_rows(shortest), caption="The shortest trails", numeric=(0,))}</section>
|
||||
<section><h2>Trails by state and province</h2>
|
||||
<p>A trail that crosses several states is counted in each, so the counts add up to more than {len(records)}.</p>
|
||||
{pagekit.table(["Place", "Trails", "Routes", "Loops", "With a GPX", "Longest"], place_rows, caption="Trails by state and province", numeric=(1, 2, 3, 4))}</section>
|
||||
<p class="finder__foot">Lengths are the published figures, which are check values, not measured from a track. See the
|
||||
<a href="/method/">method</a>. <a href="/lists/longest/">The longest trails</a> and
|
||||
<a href="/lists/under-100-miles/">the shortest</a> have their own lists.</p>
|
||||
</div>""")
|
||||
desc = common.cut_at_word(
|
||||
f"The {len(records)} long hiking trails by length, climb and place: the longest and shortest, rankings by high point and "
|
||||
f"climbing, and trails by state and province.", common.DESCRIPTION_LIMIT)
|
||||
return "Long Hiking Trails by the Numbers", desc, Markup(body)
|
||||
@@ -0,0 +1,153 @@
|
||||
"""A paragraph built from the records that a page lists: what the set holds.
|
||||
|
||||
facts(recs, records) count, longest and shortest, loops and routes, times, terrain,
|
||||
holders, highest point, and how many have a GPX
|
||||
|
||||
Every figure is counted from the records, and a sentence is left out when the records
|
||||
give it nothing to say. No trail is named here: the longest and the shortest are found
|
||||
by length. Used by the place pages and the list pages, so none is a bare list.
|
||||
"""
|
||||
from . import browse, common, facets, hike, related, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
|
||||
def _plural(n, word):
|
||||
return f"{n} {word}{'' if n == 1 else 's'}"
|
||||
|
||||
|
||||
def _name_link(rec):
|
||||
return f'<a href="{esc(common.trail_path(rec))}">{esc(common.plain_name(rec))}</a>'
|
||||
|
||||
|
||||
def _miles(rec):
|
||||
return f'{words.fmt_int(rec["derived"]["length_mi"])} miles ({words.fmt_int(rec["length_km"])} km)'
|
||||
|
||||
|
||||
def _join(parts):
|
||||
return words.join_names(parts)
|
||||
|
||||
|
||||
def _list_link(records, key, label, n):
|
||||
link = related.list_link(records, key)
|
||||
text = f"{esc(label)} ({n})"
|
||||
return f'<a href="{esc(link[0])}">{text}</a>' if link else text
|
||||
|
||||
|
||||
def terrain_counts(recs):
|
||||
"""[(terrain value, how many of recs)], most first, for the terrain the records name."""
|
||||
counts = {}
|
||||
for r in recs:
|
||||
for t in facets.terrain(r):
|
||||
counts[t] = counts.get(t, 0) + 1
|
||||
return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
|
||||
|
||||
|
||||
def holder_counts(recs, records):
|
||||
"""[(list, how many of recs)] for the lists about standing and holder (olt/browse.py): the
|
||||
ones a trail is in by what its designation says."""
|
||||
out = []
|
||||
for lst, members in browse.shown(records):
|
||||
if lst.group not in ("standing", "holder") or lst.key == "routes":
|
||||
continue
|
||||
ids = {m["id"] for m in members}
|
||||
k = sum(1 for r in recs if r["id"] in ids)
|
||||
if k:
|
||||
out.append((lst, k))
|
||||
return out
|
||||
|
||||
|
||||
def facts(recs, records):
|
||||
"""The summary paragraphs (Markup) for a set of trails. Empty for no trails."""
|
||||
if not recs:
|
||||
return Markup("")
|
||||
by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"]))
|
||||
shortest, longest = by_length[0], by_length[-1]
|
||||
sentences = []
|
||||
if len(recs) > 1:
|
||||
sentences.append(f"The longest is {_name_link(longest)}, {_miles(longest)}. "
|
||||
f"The shortest is {_name_link(shortest)}, {_miles(shortest)}.")
|
||||
else:
|
||||
sentences.append(f"{_name_link(longest)} is {_miles(longest)} long.")
|
||||
loops = sum(1 for r in recs if facets.shape(r) == "loop")
|
||||
routes = [r for r in recs if facets.kind(r) == "route"]
|
||||
parts = []
|
||||
if loops:
|
||||
parts.append(_plural(loops, "loop"))
|
||||
if routes:
|
||||
authors = {facets.author(r) for r in routes if facets.author(r)}
|
||||
parts.append(f"{_plural(len(routes), 'route')}" + (f" by {_plural(len(authors), 'author')}" if authors else ""))
|
||||
if parts and len(recs) > 1:
|
||||
sentences.append(f"{_join(parts)[:1].upper()}{_join(parts)[1:]}.")
|
||||
paragraphs = [" ".join(sentences)]
|
||||
|
||||
more = []
|
||||
timed = sorted(recs, key=lambda r: facets.time_days(r)[:2])
|
||||
if len(recs) > 1:
|
||||
quick, slow = timed[0], timed[-1]
|
||||
more.append(f"The quickest to walk whole is {_name_link(quick)}, {facets.time_text(quick).lower()}, "
|
||||
f"and the slowest is {_name_link(slow)}, {facets.time_text(slow).lower()}.")
|
||||
terrain = terrain_counts(recs)
|
||||
if terrain:
|
||||
shown = _join(
|
||||
f'{_list_link(records, "terrain-" + t, words.TERRAIN[t].lower(), n)}' for t, n in terrain[:4])
|
||||
have = sum(1 for r in recs if facets.terrain(r))
|
||||
more.append(f"Terrain is on file for {have} of them; the most common is {shown}.")
|
||||
holders = holder_counts(recs, records)
|
||||
if holders:
|
||||
more.append("By designation: " + _join(_list_link(records, lst.key, lst.title, k) for lst, k in holders) + ".")
|
||||
high = [(hike.table(r).get("high_point_m"), r) for r in recs if isinstance(hike.table(r).get("high_point_m"), (int, float))]
|
||||
if high:
|
||||
m, top = max(high, key=lambda t: (t[0], t[1]["id"]))
|
||||
more.append(f"The highest point stated is {words.elevation(m)}, on {_name_link(top)}.")
|
||||
if more:
|
||||
paragraphs.append(" ".join(more))
|
||||
return Markup("".join(f"<p>{p}</p>" for p in paragraphs))
|
||||
|
||||
|
||||
DETAIL_MAX = 3 # a page with this many trails or fewer gets a paragraph on each, so it is not a bare list
|
||||
|
||||
|
||||
def _rest_of_summary(rec):
|
||||
text = hike.summary(rec)
|
||||
first = hike.first_sentence(text)
|
||||
return text[len(first):].strip() if text.startswith(first) else ""
|
||||
|
||||
|
||||
def detail(rec):
|
||||
"""One paragraph (HTML) on a trail from its own record: what it is, its ends, its places, its time,
|
||||
high point and season, then the rest of its summary and its permit sentence. Only what the record has."""
|
||||
h = hike.table(rec)
|
||||
kind = "route" if facets.kind(rec) == "route" else "trail"
|
||||
places = ", ".join(words.region_name(c) for c in rec.get("regions", []))
|
||||
ends = hike.ends(rec)
|
||||
where = ""
|
||||
if ends:
|
||||
label, value = ends
|
||||
if isinstance(value, tuple):
|
||||
where = f", from {esc(value[0])} to {esc(value[1])}"
|
||||
elif label == "Loop":
|
||||
where = f", a loop that {esc(value[:1].lower() + value[1:])}"
|
||||
author = facets.author(rec)
|
||||
what = f"a route by {esc(author)}" if author else f"a {kind}"
|
||||
out = [f"<strong>{esc(common.plain_name(rec))}</strong> is {what} of {_miles(rec)}{where}, in {esc(places)}."]
|
||||
out.append(f"The usual time to walk it whole is {esc(facets.time_text(rec).lower())}"
|
||||
f"{', as a source states it' if not facets.time_days(rec)[2] else ', estimated from its length'}.")
|
||||
name, m = h.get("high_point", ""), h.get("high_point_m")
|
||||
if isinstance(m, (int, float)) and not isinstance(m, bool):
|
||||
out.append(f"Its high point is {esc(name + ', ') if name else ''}{words.elevation(m)}.")
|
||||
season = facets.season_text(rec)
|
||||
if season:
|
||||
out.append(f"Season: {esc(season)}.")
|
||||
rest = _rest_of_summary(rec)
|
||||
if rest:
|
||||
out.append(f'<span class="record-text">{esc(rest)}</span>')
|
||||
if h.get("permit"):
|
||||
out.append(f'Permit: <span class="record-text">{esc(common.sentence(h["permit"]))}</span>')
|
||||
return " ".join(out)
|
||||
|
||||
|
||||
def details(recs):
|
||||
"""The paragraphs on each trail, under a heading, for a page with few trails; "" for none."""
|
||||
if not recs or len(recs) > DETAIL_MAX:
|
||||
return Markup("")
|
||||
return Markup("<h2>In more detail</h2>" + "".join(f"<p>{detail(r)}</p>" for r in recs))
|
||||
+41
-10
@@ -1,12 +1,15 @@
|
||||
"""PNG logo thumbnails for the list pages.
|
||||
"""PNG logo thumbnails for the list and trail 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.
|
||||
web/thumbs/<id>.png is made by web/tools/make_thumbs.py and committed, from a
|
||||
PNG logo or (where the logo is a vector) an SVG one. The pages step copies it to
|
||||
trails/<id>/shield-thumb.png, and the pages show that copy at its real pixel size
|
||||
(read from the PNG header; no image library), so every logo <img> has a width and
|
||||
height. A logo with no thumbnail falls back to the full-size file, with a
|
||||
warning: a PNG at its own size, an SVG at the size its own viewBox gives
|
||||
(svg_size), scaled to fit within THUMB_MAX.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import sys
|
||||
@@ -15,6 +18,7 @@ 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"
|
||||
THUMB_MAX = 256 # the longest side of a thumbnail, as make_thumbs.py draws it
|
||||
|
||||
|
||||
def png_size(path):
|
||||
@@ -26,17 +30,44 @@ def png_size(path):
|
||||
return struct.unpack(">II", head[16:24])
|
||||
|
||||
|
||||
_SVG_TAG = re.compile(r"<svg\b[^>]*>", re.S)
|
||||
_NUMBER = r"(-?\d*\.?\d+(?:e-?\d+)?)"
|
||||
|
||||
|
||||
def svg_size(path):
|
||||
"""(width, height), in whole pixels fitting within THUMB_MAX x THUMB_MAX, for an
|
||||
SVG file: the shape of its viewBox, or of its width and height where it has no
|
||||
viewBox. The <img> sets only the shape (the page's CSS sizes the plate)."""
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
tag = _SVG_TAG.search(f.read(4096))
|
||||
if not tag:
|
||||
raise ValueError(f"{path} is not an SVG file")
|
||||
tag = tag.group(0)
|
||||
box = re.search(r'viewBox\s*=\s*"\s*' + (r"[\s,]+".join([_NUMBER] * 4)) + r'\s*"', tag)
|
||||
if box:
|
||||
w, h = float(box.group(3)), float(box.group(4))
|
||||
else:
|
||||
dims = [re.search(r'\b' + k + r'\s*=\s*"\s*' + _NUMBER, tag) for k in ("width", "height")]
|
||||
if not all(dims):
|
||||
raise ValueError(f"{path} gives neither a viewBox nor a width and height")
|
||||
w, h = float(dims[0].group(1)), float(dims[1].group(1))
|
||||
if w <= 0 or h <= 0:
|
||||
raise ValueError(f"{path} has an empty size")
|
||||
scale = THUMB_MAX / max(w, h)
|
||||
return max(1, round(w * scale)), max(1, round(h * scale))
|
||||
|
||||
|
||||
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.
|
||||
rec["derived"]["logo_img"] = {"src", "width", "height"}, the image the pages
|
||||
show. Without a 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 not shield.endswith((".png", ".svg")):
|
||||
if os.path.isfile(dest):
|
||||
os.remove(dest)
|
||||
return
|
||||
@@ -50,5 +81,5 @@ def prepare(rec, out_dir, repo_root, thumb_dir=THUMB_DIR):
|
||||
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)
|
||||
width, height = svg_size(path) if path.endswith(".svg") else png_size(path)
|
||||
rec["derived"]["logo_img"] = {"src": src, "width": width, "height": height}
|
||||
+238
-8
@@ -8,7 +8,7 @@ import os
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
from . import browse, common, elevation, facets, hike, related, words
|
||||
from . import browse, common, elevation, facets, hike, related, seo, words
|
||||
from .layout import OUTDOOR_STYLE
|
||||
from .markup import Markup, esc
|
||||
|
||||
@@ -94,6 +94,7 @@ def org_name(text):
|
||||
|
||||
# Page head ------------------------------------------------------------------
|
||||
|
||||
|
||||
def kind_word(rec):
|
||||
return "route" if common.is_route(rec) else "trail"
|
||||
|
||||
@@ -127,6 +128,20 @@ def lead_line(rec):
|
||||
return rec.get("designation", "")
|
||||
|
||||
|
||||
def lead_html(rec, lead, author_links=None):
|
||||
"""The lead line as HTML; on a route, the author's name in it links to the author's page
|
||||
(author_links: {credit: [(name, path)]} from olt/authors.py)."""
|
||||
links = (author_links or {}).get(facets.author(rec)) if common.is_route(rec) else None
|
||||
if not links:
|
||||
return common.rich(lead)
|
||||
text = str(esc(lead))
|
||||
for name, href in links:
|
||||
n = str(esc(name))
|
||||
if n in text:
|
||||
text = text.replace(n, f'<a href="{esc(href)}">{n}</a>', 1)
|
||||
return Markup(text)
|
||||
|
||||
|
||||
def route_definition():
|
||||
"""What a route is, one tap away from the Kind line of a route's page (no script needed)."""
|
||||
return Markup(f'<details class="define"><summary>What is a route?</summary>'
|
||||
@@ -150,7 +165,215 @@ def official_link(rec):
|
||||
return None
|
||||
|
||||
|
||||
def page_head(rec):
|
||||
# The kinds of country, as an adjective before "country": "forest and alpine country".
|
||||
TERRAIN_ADJECTIVE = {"alpine": "alpine", "forest": "forest", "desert": "desert", "coast": "coastal",
|
||||
"prairie": "prairie", "canyon": "canyon", "tundra": "tundra", "lakes": "lake",
|
||||
"farmland": "farmland"}
|
||||
# What the walking is (docs/schema.md `travel`).
|
||||
WALKING_ALONE = {
|
||||
"trail": "It is on built or maintained trail all or nearly all the way.",
|
||||
"trail-and-road": "It is on trail, with long stretches on roads.",
|
||||
"some-cross-country": "It is mostly on trail or road, with stretches that have no trail.",
|
||||
"mostly-cross-country": "It has no trail for most of the way.",
|
||||
}
|
||||
# An author's name that reads as a name in a sentence: no nickname in quotes, no note, no company.
|
||||
PLAIN_AUTHOR = re.compile(r"[^\"();]{1,40}")
|
||||
# A designation that is only a kind of trail and a year: "National Scenic Trail (1968)".
|
||||
DESIGNATION_YEAR = re.compile(r"^(National [A-Z][a-z]+ Trail) \((?:(designated|certified) )?(\d{4})\)$")
|
||||
GPX_CLAUSE = {
|
||||
"here": "this page has a GPX of the track to download",
|
||||
"partial": "this page has a GPX of part of the track to download",
|
||||
"free": "its author publishes a GPX free of charge, which this site does not host",
|
||||
"sold": "its author sells a GPX, which this site does not host",
|
||||
"unpublished": "no GPX of it is published",
|
||||
}
|
||||
|
||||
|
||||
def _name_html(rec):
|
||||
"""The name for the start of a sentence: "The Appalachian Trail", with no "The" before a
|
||||
name that has one or is not in English; marked with its language when it is not English."""
|
||||
plain = common.plain_name(rec)
|
||||
lang = rec.get("derived", {}).get("name_lang", "")
|
||||
if rec.get("common_name") or not lang:
|
||||
text = esc(plain)
|
||||
else:
|
||||
text = f'<span lang="{esc(lang)}">{esc(plain)}</span>'
|
||||
if lang or plain.lower().startswith("the "):
|
||||
return Markup(text)
|
||||
return Markup("The " + text)
|
||||
|
||||
|
||||
MAX_BRIEF = 4 # sentences in the "In brief" paragraph
|
||||
MONTH_WORDS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
|
||||
SEASON_WORDS = ("spring", "summer", "fall", "autumn", "winter", "late", "early", "mid", "from", "about")
|
||||
SENTENCE_VERBS = re.compile(r"\b(is|are|can|start|starts|hikes?|hiked|travelled|traveled|bring|brings|closed|best)\b", re.I)
|
||||
|
||||
|
||||
def season_sentence(rec):
|
||||
"""("range", "The usual season is May to July") for a season that is a range of months or
|
||||
seasons, ("sentence", "Northbound hikes start late February to early April") for one the record
|
||||
already words as a sentence, or None when the record has none or it is too long to say briefly.
|
||||
The caller adds the full stop. Only the record's own words are used."""
|
||||
text = facets.season_text(rec).strip().rstrip(". ")
|
||||
if not text:
|
||||
return None
|
||||
if re.search(r"[;:]", text): # "Spring and fall; summers tend to be humid": the range, then a note
|
||||
head = re.split(r"[;:]", text, maxsplit=1)[0].strip()
|
||||
if not SENTENCE_VERBS.search(head) or len(text) > 110:
|
||||
text = head
|
||||
if len(text) > 110: # a long note that does not break at a clause stays in "At a glance"
|
||||
return None
|
||||
if text.lower() == "all year":
|
||||
return ("sentence", "It can be walked all year")
|
||||
if SENTENCE_VERBS.search(text) and not text.lower().startswith(("from", "about", "early", "late", "mid")) or \
|
||||
text.split()[0].lower() in ("northbound", "the", "best", "hikers"):
|
||||
return ("sentence", text[:1].upper() + text[1:])
|
||||
first = text.split()[0].lower().split("-")[0]
|
||||
if first in SEASON_WORDS:
|
||||
text = text[:1].lower() + text[1:]
|
||||
return ("range", f"The usual season is {text}")
|
||||
|
||||
|
||||
def permit_sentence(rec):
|
||||
"""The record's permit text as one sentence, when it is short and says one thing; else ""."""
|
||||
text = common.sentence(hike.table(rec).get("permit", ""))
|
||||
if not text or len(text) > 75 or text.count(".") > 1 or ";" in text:
|
||||
return ""
|
||||
return text
|
||||
|
||||
|
||||
def brief_sentences(rec):
|
||||
"""The "In brief" paragraph as a list of sentences in HTML, from the record's own fields only.
|
||||
A fact the record lacks is left out. At most MAX_BRIEF sentences, in the order a searcher
|
||||
wants them: what it is and where, how long and how long it takes, the highest point and climb,
|
||||
when to go, and whether there is a GPX. Facts that do not fit stay in "At a glance"."""
|
||||
h = hike.table(rec)
|
||||
route = common.is_route(rec)
|
||||
shape = facets.shape(rec)
|
||||
mi = words.fmt_int(rec["derived"]["length_mi"])
|
||||
km = words.fmt_km(rec["length_km"])
|
||||
terrain = [TERRAIN_ADJECTIVE[t] for t in facets.terrain(rec)]
|
||||
walking = facets.walking(rec)
|
||||
country = f"{words.join_names(terrain)} country" if terrain else ""
|
||||
items = [] # (priority, display position, sentence); the lowest priorities are kept
|
||||
|
||||
# What it is, how long, where.
|
||||
tail = ""
|
||||
name = common.plain_name(rec)
|
||||
if route:
|
||||
who, year = facets.author(rec), rec.get("route", {}).get("year")
|
||||
if not PLAIN_AUTHOR.fullmatch(who or "") or who.lower().startswith("the "):
|
||||
who = "" # a nickname, a company or a note: the line under the heading names the author in full
|
||||
noun = f"{'loop ' if shape == 'loop' else ''}route" if shape != "network" else "route network"
|
||||
noun += f" by {who}" if who else ""
|
||||
tail = f", dating from {year}," if who and year else ""
|
||||
else:
|
||||
found = DESIGNATION_YEAR.match(rec.get("designation", "").strip())
|
||||
noun = {"loop": "loop trail", "network": "trail network"}.get(shape, "trail")
|
||||
if found:
|
||||
# "National Scenic Trail (1968)": the kind and the year, unless the name already says the kind
|
||||
if found.group(1).lower() not in name.lower():
|
||||
noun = found.group(1)
|
||||
tail = f", {found.group(2) or 'designated'} in {found.group(3)},"
|
||||
article = "an" if mi.startswith("8") else "a" # "an 81-mile", "an 800-mile"
|
||||
through = f" through {country}" if country else ""
|
||||
items.append((0, 0, f"{_name_html(rec)} is {article} {esc(mi)}-mile ({esc(km)} km) {esc(noun)}"
|
||||
f"{esc(tail)}{esc(through)} {esc(place_text(rec))}."))
|
||||
unfinished = common.sentence(h.get("unfinished", ""))
|
||||
if unfinished and unfinished not in hike.summary(rec): # the lede above may already say it
|
||||
items.append((4, 1, esc(unfinished)))
|
||||
|
||||
# Where it starts and ends, and how long it usually takes.
|
||||
start, end = h.get("start", ""), h.get("end", "")
|
||||
days = hike.days(rec)
|
||||
# A place name that starts a sentence in the record reads mid-sentence in lower case.
|
||||
mid = lambda text: text[:1].lower() + text[1:] if text.startswith(("The ", "Near ")) else text # noqa: E731
|
||||
at = lambda text: "near " + text[5:] if text.startswith("Near ") else "at " + text # noqa: E731
|
||||
from_start, to_end = mid(start), mid(end)
|
||||
if shape == "loop":
|
||||
where = f"It starts and ends {at(start)}" if start else ""
|
||||
elif shape == "network":
|
||||
where = f"Most walks start {at(start)}" if start else ""
|
||||
elif start and end:
|
||||
where = f"It runs from {from_start}{',' if ',' in start else ''} to {to_end}"
|
||||
elif start:
|
||||
where = f"It starts {at(start)}"
|
||||
elif end:
|
||||
where = f"It ends {at(end)}"
|
||||
else:
|
||||
where = ""
|
||||
if where and days:
|
||||
items.append((1, 2, f"{esc(where)}, and walking all of it usually takes {esc(days)}."))
|
||||
elif where:
|
||||
items.append((1, 2, f"{esc(where)}."))
|
||||
elif days:
|
||||
items.append((1, 2, f"Walking all of it usually takes {esc(days)}."))
|
||||
|
||||
# What the walking is.
|
||||
if walking and walking != "trail": # the usual case needs no sentence
|
||||
items.append((5, 3, esc(WALKING_ALONE[walking])))
|
||||
|
||||
# Highest point and climb, with the record's own caveat where the figures come from the track.
|
||||
elev = elevation.get(rec)
|
||||
high_name, high_m = h.get("high_point", ""), h.get("high_point_m")
|
||||
high = ""
|
||||
if high_name.startswith(("Near ", "Between ", "Above ", "Along ")):
|
||||
high_name = high_name[:1].lower() + high_name[1:] # "Its highest point is near Owen Creek"
|
||||
if high_name and high_m:
|
||||
high = f"{high_name}, at {elevation.plain_elevation(high_m)}"
|
||||
elif high_name:
|
||||
high = high_name
|
||||
elif high_m:
|
||||
high = elevation.plain_elevation(high_m)
|
||||
climb = f"the track climbs {elevation.plain_elevation(elev['ascent_m'])} in total" if elev else ""
|
||||
how = "computed from the track"
|
||||
if elev and elevation.coverage_kind(elev) == "partial":
|
||||
how = (f"computed from the part of the track on file, {elevation.coverage_percent(elev)} "
|
||||
f"of the published length")
|
||||
elif elev and elevation.coverage_kind(elev) == "over":
|
||||
how = (f"computed from a track longer than the published length "
|
||||
f"({elevation.coverage_percent(elev)} of it), so the climb is overstated")
|
||||
if high and climb:
|
||||
items.append((2, 4, f"Its highest point is {esc(high)}, and {esc(climb)}, {esc(how)}."))
|
||||
elif high:
|
||||
items.append((2, 4, f"Its highest point is {esc(high)}."))
|
||||
elif elev:
|
||||
items.append((2, 4, f"Its highest point is {esc(elevation.plain_elevation(elev['highest']['m']))}, "
|
||||
f"and {esc(climb)}, {esc(how)}."))
|
||||
|
||||
# When to walk it and whether this site has a GPX: one sentence where the season is a plain range.
|
||||
clause = GPX_CLAUSE.get(facets.gpx(rec)) or ("this site has no GPX for it" + (", so see the official site" if official_link(rec) else ""))
|
||||
season = season_sentence(rec)
|
||||
if season and not re.search(r"[,;]", season[1]):
|
||||
# "The usual season is May to July, and this page has a GPX of the track to download."
|
||||
items.append((3, 5, f"{esc(season[1])}, and {esc(clause)}."))
|
||||
else:
|
||||
if season:
|
||||
items.append((3.5, 5, esc(season[1]) + "."))
|
||||
items.append((3, 6, esc(clause[:1].upper() + clause[1:]) + "."))
|
||||
permit = permit_sentence(rec)
|
||||
if permit:
|
||||
items.append((6, 7, esc(permit)))
|
||||
|
||||
# At most MAX_BRIEF sentences: the lowest priorities are kept, shown in reading order.
|
||||
kept = sorted(sorted(items, key=lambda i: (i[0], i[1]))[:MAX_BRIEF], key=lambda i: i[1])
|
||||
return [text for _, _, text in kept]
|
||||
|
||||
|
||||
def brief(rec):
|
||||
"""The "In brief" paragraph for the top of a trail page: Markup."""
|
||||
return Markup(f'<p class="trail-brief"><strong>In brief.</strong> {" ".join(brief_sentences(rec))}</p>')
|
||||
|
||||
|
||||
def checked_line(rec):
|
||||
""""Last checked 2026-11-08", as a <time>, in the page's small print; "" when the record has no date."""
|
||||
date = seo.checked(rec)
|
||||
if not date:
|
||||
return ""
|
||||
return Markup(f'<p class="note trail-checked">Last checked <time datetime="{esc(date)}">{esc(date)}</time></p>')
|
||||
|
||||
|
||||
def page_head(rec, author_links=None):
|
||||
route = common.is_route(rec)
|
||||
crumbs = ['<li><a href="/regions/">Places</a></li>']
|
||||
keys = facets.place_keys(rec)
|
||||
@@ -198,11 +421,13 @@ def page_head(rec):
|
||||
<div class="titleblock__text">
|
||||
{kicker}
|
||||
<h1>{heading}{abbr_html}</h1>
|
||||
{full_name}{f'<p class="titleblock__sub">{common.rich(lead)}</p>' if lead else ""}
|
||||
{full_name}{f'<p class="titleblock__sub">{lead_html(rec, lead, author_links)}</p>' if lead else ""}
|
||||
{define}
|
||||
</div>
|
||||
</header>
|
||||
<p class="trail-lede">{lede}</p>
|
||||
{brief(rec)}
|
||||
{checked_line(rec)}
|
||||
<p class="cluster trail-actions">{"".join(actions)}</p>
|
||||
{links_panel(rec)}
|
||||
</div>
|
||||
@@ -1256,9 +1481,11 @@ def page_title(rec, site):
|
||||
Only what is true of the page: GPX only where it has a download, a map only
|
||||
where it has a track.
|
||||
|
||||
The whole title, site name included, stays within common.TITLE_LIMIT. Pieces go in
|
||||
The title alone stays within common.TITLE_LIMIT (the site name is added to <title> only
|
||||
where the whole is within it too, see common.title_tag). Pieces go in
|
||||
this order until it fits: the kilometres, the author of a route, the word
|
||||
"map", the abbreviation, then "GPX". A route says it is a route.
|
||||
"map", the abbreviation, then "GPX". A route says it is a route. Where even that is
|
||||
too long and the name alone fits, the title is the name; the name is never cut.
|
||||
"""
|
||||
name = common.plain_name(rec)
|
||||
abbr = rec.get("short_name", "")
|
||||
@@ -1283,7 +1510,10 @@ def page_title(rec, site):
|
||||
option = text(*step)
|
||||
if option not in options:
|
||||
options.append(option)
|
||||
return common.fit_title(options, site)
|
||||
fitted = common.fit_title(options, site)
|
||||
if len(fitted) > common.title_room(site) >= len(name):
|
||||
return name # only the name fits: the length goes before the name is cut
|
||||
return fitted
|
||||
|
||||
|
||||
def places_short(rec):
|
||||
@@ -1387,7 +1617,7 @@ def onward(rec, records):
|
||||
f'<div class="onward__grid">{"".join(parts)}</div></nav>')
|
||||
|
||||
|
||||
def render(rec, site, records=None):
|
||||
def render(rec, site, records=None, author_links=None):
|
||||
"""Return (title, description, body HTML, needs_map) for one trail.
|
||||
records: every trail, for the ways onward at the foot (left out when None)."""
|
||||
has_track = common.has_line(rec)
|
||||
@@ -1397,7 +1627,7 @@ def render(rec, site, records=None):
|
||||
aside_html = (f'<aside class="detail__aside" aria-label="{"Downloads" if has_track else "Where to get the route"}">'
|
||||
f'{aside}</aside>') if aside else ""
|
||||
profile = elevation_figure(rec)
|
||||
body = f"""{page_head(rec)}
|
||||
body = f"""{page_head(rec, author_links)}
|
||||
<div class="container detail{"" if aside else " detail--no-aside"}{"" if has_map else " detail--no-map"}{" detail--with-profile" if profile else ""}">
|
||||
{glance(rec, records)}
|
||||
{map_figure(rec) if has_track else sketch_figure(rec) if sketch else empty_frame(rec)}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Two pages built from how the records point at each other and at their own history:
|
||||
|
||||
/recent/ the newest additions, and the newest changes, from each record's [[history]]
|
||||
/connected/ trails whose own words name another trail, grouped under the trail they name
|
||||
|
||||
Nothing names a trail. "Newest" is measured from the newest date the records give, never from the
|
||||
day the site is built, so a page does not change until the data does.
|
||||
"""
|
||||
import collections
|
||||
|
||||
from . import browse, common, facets, home, pagekit, related, seo
|
||||
from .markup import Markup, esc
|
||||
|
||||
RECENT = "/recent/"
|
||||
CONNECTED = "/connected/"
|
||||
ADDED_MIN = 20 # whole days of additions are shown until at least this many trails are
|
||||
CHANGE_ROWS = 30
|
||||
GROUP_MIN = 3 # a trail is a group when at least this many others name it
|
||||
|
||||
|
||||
# Recent -----------------------------------------------------------------------------
|
||||
|
||||
def added_date(rec):
|
||||
"""The date of the entry that added the record."""
|
||||
for e in rec.get("history", []):
|
||||
if isinstance(e, dict) and e.get("fields") == ["record"]:
|
||||
return str(e.get("date", ""))
|
||||
return ""
|
||||
|
||||
|
||||
def recent_added(records):
|
||||
"""[(date, [trails])], newest day first, whole days until at least ADDED_MIN trails."""
|
||||
days = collections.defaultdict(list)
|
||||
for r in records:
|
||||
d = added_date(r)
|
||||
if d:
|
||||
days[d].append(r)
|
||||
out, count = [], 0
|
||||
for d in sorted(days, reverse=True):
|
||||
out.append((d, sorted(days[d], key=lambda r: r["id"])))
|
||||
count += len(days[d])
|
||||
if count >= ADDED_MIN:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def recent_changes(records):
|
||||
"""(rows, total): the newest applied changes to a record's facts, as (date, trail, what), newest first
|
||||
and in name order within a day; and how many such changes there are."""
|
||||
found = []
|
||||
for r in records:
|
||||
for e in r.get("history", []):
|
||||
if (isinstance(e, dict) and e.get("outcome") == "applied" and e.get("fields") != ["record"]
|
||||
and e.get("date")):
|
||||
found.append((str(e["date"]), r, e.get("change", "")))
|
||||
found.sort(key=lambda t: (t[0], ), reverse=True)
|
||||
found.sort(key=lambda t: (-int(t[0].replace("-", "")), t[1]["name"].lower()))
|
||||
return found[:CHANGE_ROWS], len(found)
|
||||
|
||||
|
||||
def recent_page(records, site):
|
||||
"""(title, description, body, recs) for /recent/, or None when fewer than MIN_SIZE trails were added."""
|
||||
added = recent_added(records)
|
||||
recs = [r for _, rs in added for r in rs]
|
||||
if len(recs) < browse.MIN_SIZE:
|
||||
return None
|
||||
changes, total = recent_changes(records)
|
||||
newest = seo.newest(records)
|
||||
groups = [(f"Added {d} ({len(rs)})", rs, None) for d, rs in added]
|
||||
rows = [[d, pagekit.trail_link(r), change] for d, r, change in changes]
|
||||
lede = (f"The {len(recs)} newest additions, from each trail’s own history, and the newest of the {total} changes "
|
||||
f"made to a trail’s facts. The newest date in the data is {esc(newest)}.")
|
||||
body = (pagekit.head("Recently added and changed", lede, [("Trails", "/"), ("Lists", "/lists/")])
|
||||
+ f"""<div class="container section place">
|
||||
<section><h2>Newly added trails</h2>
|
||||
{home.results(groups=groups, top=3)}</section>
|
||||
<section><h2>Newest changes</h2>
|
||||
{pagekit.table(["Date", "Trail", "What changed"], rows, caption="The newest changes")}
|
||||
<p class="finder__foot">Each trail keeps its own history, shown at the foot of its page. The
|
||||
<a href="/data/changelog/">changelog</a> lists changes to the site and the dataset as a whole.</p></section>
|
||||
</div>""")
|
||||
title = "Recently Added Long Hiking Trails and Changes"
|
||||
desc = common.cut_at_word(f"The {len(recs)} newest long hiking trails and the newest changes to them, "
|
||||
f"from each trail's history. Newest date: {newest}.", common.DESCRIPTION_LIMIT)
|
||||
return title, desc, Markup(body), recs
|
||||
|
||||
|
||||
# Connected ------------------------------------------------------------------------------
|
||||
|
||||
def connections(records):
|
||||
"""[(trail named, [trails that name it])] for every trail that at least GROUP_MIN other trails'
|
||||
own descriptions name, most named first. Only the description names it: no sharing of a name counts."""
|
||||
graph = related._once(records, "related", lambda: related._related_graph(records))
|
||||
by_id = {r["id"]: r for r in records}
|
||||
out = []
|
||||
for rid, edges in graph.items():
|
||||
namers = [by_id[o] for o, why in edges.items() if why == "names"]
|
||||
if len(namers) >= GROUP_MIN:
|
||||
out.append((by_id[rid], sorted(namers, key=lambda r: r["id"])))
|
||||
out.sort(key=lambda t: (-len(t[1]), t[0]["id"]))
|
||||
return out
|
||||
|
||||
|
||||
def connected_page(records, site):
|
||||
"""(title, description, body, recs) for /connected/, or None when fewer than MIN_SIZE trails are in groups.
|
||||
|
||||
A trail is listed once, under the first group it belongs to (the one named by most others), so the
|
||||
rows are the trails."""
|
||||
groups = connections(records)
|
||||
seen = set()
|
||||
sections = []
|
||||
recs = []
|
||||
for named, namers in groups:
|
||||
fresh = [r for r in namers if r["id"] not in seen]
|
||||
seen.update(r["id"] for r in fresh)
|
||||
if fresh:
|
||||
sections.append((f'Trails that name <a href="{esc(common.trail_path(named))}">{common.name(named)}</a> '
|
||||
f'({len(fresh)})', fresh, None))
|
||||
recs += fresh
|
||||
if len(recs) < browse.MIN_SIZE:
|
||||
return None
|
||||
lede = (f"{len(groups)} trails that other trails’ own descriptions name. Under each one are the trails whose "
|
||||
f"own description names it, {len(recs)} trails in all, each listed once. A description names another trail when its summary, "
|
||||
f"designation, caution or route note uses that trail’s name. It does not say the two meet.")
|
||||
body = (pagekit.head("Linked long trails", lede, [("Trails", "/"), ("Lists", "/lists/")])
|
||||
+ f"""<div class="container section place">
|
||||
{home.results(groups=sections, top=2)}
|
||||
</div>""")
|
||||
title = "Linked Long Trails: Trails That Name Other Trails"
|
||||
desc = common.cut_at_word(f"{len(groups)} long trails that other trails name in their own descriptions, with the "
|
||||
f"{len(recs)} trails that name them.", common.DESCRIPTION_LIMIT)
|
||||
return title, desc, Markup(body), recs
|
||||
Reference in new issue
Block a user