Merge main into seasons-ship-3: places pages from main kept alongside the seasons; places precede history in records, this ship's changelog entry first
This commit is contained in:
commit
535d2bebaa
265 files changed
+15157
-108
No files matched your search
@@ -4,6 +4,7 @@
|
||||
collections.toml [[collection]] named sets of trails set side by side (olt/standing.py)
|
||||
[[list]] which lists the home page shows, and in what order (olt/home.py)
|
||||
authors.toml [[author]] route authors, and the words about the people among them (olt/authors.py)
|
||||
places.toml [[place]] the parks, mountain ranges and wilderness areas records name
|
||||
tools/season_blind_test.json how the judged seasons did against the seasons pages state (olt/reference.py)
|
||||
|
||||
Each is checked by tools/validate.py and described in docs/schema.md. Like left-out.toml, a file
|
||||
@@ -39,6 +40,11 @@ def authors(repo_root):
|
||||
return load(repo_root, "authors.toml", "author")
|
||||
|
||||
|
||||
def places(repo_root):
|
||||
"""The [[place]] entries of places.toml: the place registry."""
|
||||
return load(repo_root, "places.toml", "place")
|
||||
|
||||
|
||||
def lists(repo_root):
|
||||
"""The [[list]] entries of collections.toml: a list's key, and `home`, its place in the home page's row."""
|
||||
return load(repo_root, "collections.toml", "list")
|
||||
|
||||
+22
-8
@@ -240,7 +240,8 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
|
||||
|
||||
# The filters ------------------------------------------------------------------
|
||||
# One bar and one set of panels, on the home page and on every other page that shows a set of at
|
||||
# least FILTER_MIN trails (listing()). Everything is built from the page's own trails: a facet that
|
||||
# least FILTER_MIN trails (listing()), and on every park, range and wilderness page whatever its
|
||||
# size (the owner's rule: every set of trails gets the bar). Everything is built from the page's own trails: a facet that
|
||||
# cannot narrow them is left out, and an option none of them has is not written. The numbers written
|
||||
# here are for the whole set; app.js counts again from the rows on the page every time anything
|
||||
# changes, and hides an option that would show nothing (its counting is facetCounts(), which
|
||||
@@ -321,11 +322,13 @@ def _missing(records, key):
|
||||
f'{esc(facets.missing_text(without, key))} They are left out while this filter is on.</p>')
|
||||
|
||||
|
||||
def finder_form(records, c=None, steps=None, where="all"):
|
||||
def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
|
||||
"""The bar (search, Filters, Clear) and the panels: the first-rank filters, then Walking, Shape and
|
||||
GPX behind "More". records: the page's own trails. where: the Where filter's scope ("all",
|
||||
"g:<group>" on a group's page, "" for none: a state's page). A facet is written only when it can
|
||||
narrow these trails; each field carries data-facet, for app.js to hide it when it no longer can."""
|
||||
narrow these trails; each field carries data-facet, for app.js to hide it when it no longer can.
|
||||
bare_if_empty: a set that nothing can narrow gets the search box alone, with no Filters
|
||||
button and no empty panel."""
|
||||
c = c or counts(records)
|
||||
steps = steps or length_steps(records)
|
||||
km_steps = length_steps(records, "km")
|
||||
@@ -408,6 +411,16 @@ def finder_form(records, c=None, steps=None, where="all"):
|
||||
{"".join(more)}
|
||||
</div>
|
||||
</details>""" if more else ""
|
||||
if bare_if_empty and not first and not more:
|
||||
return """<form class="filters" id="finder-form" role="search" aria-label="Find a trail">
|
||||
<div class="filters__bar">
|
||||
<div class="filters__search field">
|
||||
<label class="vh" for="q">Search</label>
|
||||
<input class="input" id="q" name="q" type="search" placeholder="Search by name, place or author" autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<button class="button button--quiet filters__clear" type="reset" hidden>Clear</button>
|
||||
</div>
|
||||
</form>"""
|
||||
return f"""<form class="filters" id="finder-form" role="search" aria-label="Find a trail">
|
||||
<div class="filters__bar">
|
||||
<div class="filters__search field">
|
||||
@@ -430,14 +443,15 @@ def finder_form(records, c=None, steps=None, where="all"):
|
||||
</form>"""
|
||||
|
||||
|
||||
def listing(recs=None, *, where="all", groups=None, **kw):
|
||||
def listing(recs=None, *, where="all", groups=None, always=False, **kw):
|
||||
"""The rows of a page that shows a set of trails, with the filter bar over them when the set
|
||||
has at least FILTER_MIN trails (else results() alone). where: the Where filter's scope
|
||||
(finder_form). The other arguments are results()'s."""
|
||||
has at least FILTER_MIN trails (else results() alone); with always, whatever its size (the
|
||||
bar then holds only the filters that have something to offer). where: the Where filter's
|
||||
scope (finder_form). The other arguments are results()'s."""
|
||||
trails = [r for g in groups for r in g[1]] if groups is not None else list(recs)
|
||||
if len(trails) < FILTER_MIN:
|
||||
if len(trails) < FILTER_MIN and not always:
|
||||
return results(recs, groups=groups, **kw)
|
||||
return Markup(f"""<div class="finder__bar">{finder_form(trails, where=where)}</div>
|
||||
return Markup(f"""<div class="finder__bar">{finder_form(trails, where=where, bare_if_empty=always)}</div>
|
||||
{results(recs, groups=groups, finder=True, **kw)}""")
|
||||
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ NAV = (
|
||||
# Pages with no header item of their own, and the item they sit under. A trail's page is part of
|
||||
# Trails; the dataset pages are part of About and are linked from the About hub and the footer.
|
||||
NAV_PARENT = {"/trails/": "/",
|
||||
"/parks/": "/regions/", "/ranges/": "/regions/", "/wilderness/": "/regions/",
|
||||
"/sources/": "/about/", "/logos/": "/about/", "/data/": "/about/",
|
||||
"/left-out/": "/about/", "/method/": "/about/", "/glossary/": "/about/"}
|
||||
# Under Lists: the lists (Routes among them), the tables and rankings, the authors and the views of
|
||||
|
||||
+29
-4
@@ -31,11 +31,17 @@ import os
|
||||
import shutil
|
||||
|
||||
from .markup import esc
|
||||
from . import authors, browse, cards, datafiles, docs, facets, feed, home, layout, leftout, pagekit, placefacets, reference, regions, saved, seo, site as site_settings, sketch, standing, thumbs, trail, views
|
||||
from . import authors, browse, cards, datafiles, docs, facets, feed, home, layout, leftout, pagekit, placefacets, placepages, places, reference, regions, saved, searchtext, seo, site as site_settings, sketch, standing, thumbs, trail, views
|
||||
|
||||
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ASSETS_DIR = os.path.join(WEB_DIR, "assets")
|
||||
|
||||
# Builders of further place pages, run after the state and group pages. Each takes
|
||||
# (records, site, repo_root) and returns pages as (path, title, description, body,
|
||||
# needs_map, recs); each page is added like a state page and reaches the sitemap
|
||||
# through region_paths.
|
||||
EXTRA_PAGE_BUILDERS = (placepages.build,)
|
||||
|
||||
|
||||
def copy_assets(out_dir, assets_dir=ASSETS_DIR):
|
||||
"""Copy web/assets/ to <out>/assets/, replacing what was there. The fingerprinted files
|
||||
@@ -93,13 +99,24 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
everything = seo.newest(records)
|
||||
author_links = authors.link_map(records, repo_root)
|
||||
home.use_authors(author_links)
|
||||
# The parks, ranges and wilderness areas (olt/places.py): which have a page, for
|
||||
# the links on trail and state pages and the hub, and every trail's place names
|
||||
# for search, a page or not.
|
||||
registry = places.load(repo_root)
|
||||
place_infos = places.collect(records, registry)
|
||||
search_names = {}
|
||||
for key, recs in places.membership(records, registry).items():
|
||||
for r in recs:
|
||||
search_names.setdefault(r["id"], []).append(registry[key].get("name", ""))
|
||||
searchtext.use_place_names(search_names)
|
||||
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, author_links=author_links)
|
||||
title, description, body, needs_map = trail.render(
|
||||
rec, site, records, author_links=author_links, place_infos=place_infos)
|
||||
path = f"/trails/{rec['id']}/"
|
||||
card, card_alt = cards.prepare(rec, out_dir)
|
||||
layout.write_page(out_dir, path, layout.layout(
|
||||
@@ -134,13 +151,15 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
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)
|
||||
t, d, b = regions.regions_index_page(records, site, infos=place_infos)
|
||||
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):
|
||||
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)
|
||||
t, d, b, needs_map = regions.region_page(
|
||||
slug, records, site, facet_pages=here,
|
||||
place_links=regions.place_links_for(by_slug[slug]["key"], place_infos))
|
||||
path = f"/regions/{slug}/"
|
||||
region_paths.append(path)
|
||||
add(path, t, d, b, maps=needs_map, recs=by_slug[slug]["records"])
|
||||
@@ -159,6 +178,12 @@ def render_site(records, out_dir, repo_root, site=None):
|
||||
path = regions.group_path(g)
|
||||
region_paths.append(path)
|
||||
add(path, t, d, b, maps=needs_map, recs=recs)
|
||||
# Further place pages (parks, ranges and wilderness areas, olt/placepages.py).
|
||||
for builder in EXTRA_PAGE_BUILDERS:
|
||||
for built in builder(records, site, repo_root):
|
||||
region_paths.append(built.path)
|
||||
add(built.path, built.title, built.description, built.body,
|
||||
maps=built.needs_map, recs=built.recs)
|
||||
# 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)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Pages for national parks, mountain ranges and wilderness areas:
|
||||
/parks/<slug>/, /ranges/<slug>/, /wilderness/<slug>/
|
||||
|
||||
The page itself is regions.place_page, the same one a state page uses; this module
|
||||
holds only what is different here, as a regions.PageKind each: plain A to Z rows,
|
||||
the states-and-provinces Where filter, the map opened on the registry's box, and
|
||||
no whole-trail figure given as the place's (the summary's place has no state keys).
|
||||
olt/pages.py runs build() through its EXTRA_PAGE_BUILDERS. A place is here only
|
||||
with three or more trails (olt/places.py collect)."""
|
||||
from collections import namedtuple
|
||||
|
||||
from . import common, places, regions, words
|
||||
from .markup import esc
|
||||
|
||||
Built = namedtuple("Built", ("path", "title", "description", "body", "needs_map", "recs"))
|
||||
|
||||
|
||||
def _in_name(info):
|
||||
return places.in_name(info)
|
||||
|
||||
|
||||
def _phrase(info):
|
||||
""""in the Wind River Range", "on the Colorado Plateau", "along the Mogollon Rim"."""
|
||||
return places.in_phrase(info)
|
||||
|
||||
|
||||
def _kicker(info):
|
||||
label = info.get("label") or places.label_of(info)
|
||||
names = places.state_names(info)
|
||||
return f"{label} · {words.join_names(names)}" if names else label
|
||||
|
||||
|
||||
def _crumbs(info):
|
||||
return '<li><a href="/">Trails</a></li><li><a href="/regions/">Places</a></li>'
|
||||
|
||||
|
||||
def _lede(info, recs, n_gpx):
|
||||
return f"{regions._plural(len(recs))} {esc(_phrase(info))}, {n_gpx} with a GPX here."
|
||||
|
||||
|
||||
def _title_options(info, recs, site):
|
||||
"""Every title keeps the count of trails. The state goes first when the title is too long
|
||||
(and is never there when the name already holds it); a title that is still over the cap
|
||||
keeps its count rather than lose it. "Long Hikes" and the preposition are never cut."""
|
||||
count = regions._plural(len(recs), "Trail")
|
||||
prep = places.prep_of(info)
|
||||
return [f"Long Hikes {prep} {info['title_name']}: {count}",
|
||||
f"Long Hikes {prep} {info['name']}: {count}"]
|
||||
|
||||
|
||||
def _description(info, recs):
|
||||
n_gpx = regions._gpx_count(recs)
|
||||
routes = sum(1 for r in recs if common.is_route(r))
|
||||
what = regions._plural(len(recs), "trail") + (" and routes" if 0 < routes < len(recs) else "")
|
||||
if routes == len(recs):
|
||||
what = regions._plural(len(recs), "route")
|
||||
what = what[:1].upper() + what[1:]
|
||||
gpx = (f" {regions._with_gpx(n_gpx, len(recs))[:1].upper()}{regions._with_gpx(n_gpx, len(recs))[1:]}."
|
||||
if n_gpx else "")
|
||||
by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"]))
|
||||
# No state keys: a trail that runs on out of the place is never sized as the place's.
|
||||
first = (f"{what} {places.prep_of(info)} {info['title_name']}, from {common.plain_name(by_length[0])}, "
|
||||
f"{regions.trail_miles(by_length[0], ())}, to {common.plain_name(by_length[-1])}, "
|
||||
f"{regions.trail_miles(by_length[-1], ())}.")
|
||||
return regions._fit([first + gpx, first, f"{what} {places.prep_of(info)} {info['title_name']}.{gpx}"])
|
||||
|
||||
|
||||
def _nav(info, records, recs, facet_pages):
|
||||
return (regions._lists_nav(_in_name(info), recs, records, _phrase(info))
|
||||
+ regions._facet_nav(_in_name(info), facet_pages, _phrase(info)))
|
||||
|
||||
|
||||
def _kind():
|
||||
return regions.PageKind(
|
||||
kicker=_kicker, crumbs=_crumbs, lede=_lede, where="all", wholly=False,
|
||||
facts_place=lambda info: (_in_name(info), ()), title_options=_title_options,
|
||||
description=_description, box=lambda info: info.get("box"), nav=_nav,
|
||||
in_name=_in_name, phrase=_phrase, always_filters=True)
|
||||
|
||||
|
||||
PARK = _kind()
|
||||
RANGE = _kind()
|
||||
WILDERNESS = _kind()
|
||||
PAGE_KINDS = {"park": PARK, "range": RANGE, "wilderness": WILDERNESS}
|
||||
|
||||
|
||||
def build(records, site, repo_root):
|
||||
"""[Built] for every place with a page, parks then ranges then wilderness areas,
|
||||
each A to Z. The plug-in point's shape (olt/pages.py EXTRA_PAGE_BUILDERS)."""
|
||||
infos = places.collect(records, places.load(repo_root))
|
||||
out = []
|
||||
for info in sorted(infos.values(),
|
||||
key=lambda i: (places.KIND_ORDER[i["kind"]], i["name"].lower())):
|
||||
title, description, body, needs_map = regions.place_page(
|
||||
info, records, site, PAGE_KINDS[info["kind"]])
|
||||
out.append(Built(info["path"], title, description, body, needs_map, info["records"]))
|
||||
return out
|
||||
@@ -0,0 +1,237 @@
|
||||
"""National parks, mountain ranges and wilderness areas: the places.toml registry
|
||||
and which trails are in each place (the [[place]] tables of the records).
|
||||
|
||||
Membership is closed over the registry's `within` here, at build time: a trail in a
|
||||
nested range is in every parent range too, though its record never names a parent.
|
||||
A place has a page only with PAGE_MIN or more trails, counting measured (`track`)
|
||||
and hand-entered (`stated`) placements alike. Below that it has no page and no link.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
|
||||
from . import datafiles, facets, words
|
||||
|
||||
PAGE_MIN = 3
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Kind:
|
||||
key: str # the registry kind: "park", "range", "wilderness"
|
||||
segment: str # the first part of the page's address: /parks/<slug>/
|
||||
hub_title: str # the Places hub section's heading
|
||||
noun: str # one place of this kind, for a page's kicker
|
||||
|
||||
|
||||
KINDS = {
|
||||
"park": Kind("park", "parks", "Parks", "Park"),
|
||||
"range": Kind("range", "ranges", "Mountain ranges", "Mountain range"),
|
||||
"wilderness": Kind("wilderness", "wilderness", "Wilderness areas", "Wilderness area"),
|
||||
}
|
||||
KIND_ORDER = {key: i for i, key in enumerate(KINDS)}
|
||||
|
||||
|
||||
def load(repo_root):
|
||||
"""The place registry of places.toml, keyed (kind, slug). Slugs repeat across kinds."""
|
||||
out = {}
|
||||
for e in datafiles.places(repo_root):
|
||||
if isinstance(e, dict) and e.get("kind") and e.get("slug"):
|
||||
out[(e["kind"], e["slug"])] = e
|
||||
return out
|
||||
|
||||
|
||||
def path(kind, slug):
|
||||
"""The page of a place: /parks/glacier-national-park/, /ranges/wind-river-range/, /wilderness/<slug>/."""
|
||||
return f"/{KINDS[kind].segment}/{slug}/"
|
||||
|
||||
|
||||
def _parents(registry):
|
||||
"""(kind, slug) -> its parent (kind, slug)s. A `within` parent is always a range."""
|
||||
return {key: [("range", s) for s in (e.get("within") or []) if ("range", s) in registry]
|
||||
for key, e in registry.items()}
|
||||
|
||||
|
||||
def _closure(key, parents):
|
||||
"""The place itself and every ancestor, each once (a `within` cycle cannot loop)."""
|
||||
seen, stack = [], [key]
|
||||
while stack:
|
||||
k = stack.pop(0)
|
||||
if k in seen:
|
||||
continue
|
||||
seen.append(k)
|
||||
stack += parents.get(k, [])
|
||||
return seen
|
||||
|
||||
|
||||
def membership(records, registry):
|
||||
"""(kind, slug) -> the records in the place, deduplicated and A to Z, closed over
|
||||
`within`. Every registry place is a key, with no records when none is in it. A place
|
||||
a record names that the registry does not hold is ignored (the validator refuses it)."""
|
||||
parents = _parents(registry)
|
||||
out = {key: [] for key in registry}
|
||||
seen = {key: set() for key in registry}
|
||||
for rec in records:
|
||||
for p in rec.get("place") or []:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
key = (p.get("kind"), p.get("slug"))
|
||||
if key not in registry:
|
||||
continue
|
||||
for k in _closure(key, parents):
|
||||
if rec["id"] not in seen[k]:
|
||||
seen[k].add(rec["id"])
|
||||
out[k].append(rec)
|
||||
for recs in out.values():
|
||||
recs.sort(key=facets.sort_name)
|
||||
return out
|
||||
|
||||
|
||||
def _state_key(code):
|
||||
""""WY" -> "US-WY"; a code already carrying its country ("us-wy") is put in the same form."""
|
||||
code = str(code or "").strip()
|
||||
if "-" in code:
|
||||
country, _, rest = code.partition("-")
|
||||
return f"{country.upper()}-{rest.upper()}"
|
||||
country = words.region_country(code)
|
||||
return f"{country}-{code}" if country else code
|
||||
|
||||
|
||||
def state_names(info):
|
||||
"""The full names of the states and provinces a place is in ("Wyoming"), from its `where`."""
|
||||
return [words.region_name(_state_key(c).split("-", 1)[-1]) for c in info.get("where") or []]
|
||||
|
||||
|
||||
DEFAULT_PREP = {"park": "in", "range": "in the", "wilderness": "in the"}
|
||||
|
||||
|
||||
def label_of(entry_or_info):
|
||||
"""The page's kind word, from the registry's `label` or else the kind's own."""
|
||||
return entry_or_info.get("label") or KINDS[entry_or_info["kind"]].noun
|
||||
|
||||
|
||||
def prep_of(entry_or_info):
|
||||
"""The preposition a title or lede uses, from the registry's `prep` or else the kind's own:
|
||||
"in the" for a range or a wilderness area, "in" for a park; "on the Colorado Plateau",
|
||||
"along the Mogollon Rim" where the registry says so."""
|
||||
return entry_or_info.get("prep") or DEFAULT_PREP[entry_or_info["kind"]]
|
||||
|
||||
|
||||
def in_name(info):
|
||||
"""The name as it reads after a verb or "through" ("the Wind River Range"): with "the"
|
||||
when the place's preposition has one, as the plain name where it has not."""
|
||||
name = info["name"]
|
||||
if prep_of(info).endswith(" the") and not name.lower().startswith("the "):
|
||||
return f"the {name}"
|
||||
return name
|
||||
|
||||
|
||||
def in_phrase(info):
|
||||
"""The preposition and the name, as a title or a lede has it: "in the Wind River Range",
|
||||
"on the Colorado Plateau", "along the Mogollon Rim", "in Yosemite National Park"."""
|
||||
return f"{prep_of(info)} {info['name']}"
|
||||
|
||||
|
||||
def title_name(info):
|
||||
"""The place as a page title names it: a park by its name alone; a range or a wilderness
|
||||
area in one state or province with that state spelled out ("Wind River Range, Wyoming"),
|
||||
with no state when it spans several or when the name already holds it ("Oregon Cascades",
|
||||
"California Coast Ranges")."""
|
||||
name = info["name"]
|
||||
if info.get("kind") == "park":
|
||||
return name
|
||||
names = state_names(info)
|
||||
if len(names) == 1 and names[0].lower() not in name.lower():
|
||||
return f"{name}, {names[0]}"
|
||||
return name
|
||||
|
||||
|
||||
_NAME_ENDS = (" national park", " provincial park", " wilderness area", " park", " wilderness")
|
||||
|
||||
|
||||
def _core(name):
|
||||
text = " ".join(str(name).lower().split())
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for end in _NAME_ENDS:
|
||||
if text.endswith(end) and len(text) > len(end):
|
||||
text = text[:-len(end)].strip()
|
||||
changed = True
|
||||
return text
|
||||
|
||||
|
||||
def _doubled(park_name, wild_name):
|
||||
"""True when a park and a wilderness area are the same ground under two names: one
|
||||
name holds the other, or the names differ only in the kind words at the end."""
|
||||
a, b = " ".join(str(park_name).lower().split()), " ".join(str(wild_name).lower().split())
|
||||
if a in b or b in a:
|
||||
return True
|
||||
return bool(_core(a)) and _core(a) == _core(b)
|
||||
|
||||
|
||||
_STEM_FILLER = {"national", "provincial", "park", "parks", "preserve", "wilderness", "area",
|
||||
"and", "the", "of", "mountains", "mountain", "range", "ranges"}
|
||||
|
||||
|
||||
def _stem(name):
|
||||
return {w for w in str(name).lower().replace("-", " ").split() if w not in _STEM_FILLER}
|
||||
|
||||
|
||||
def _same_stem(park_name, range_name):
|
||||
"""True when a park and a mountain range have the same name once the kind words are
|
||||
taken away: Olympic National Park and Olympic Mountains, Great Smoky Mountains National
|
||||
Park and Great Smoky Mountains. Grand Teton National Park and the Teton Range do not."""
|
||||
a, b = _stem(park_name), _stem(range_name)
|
||||
return bool(a) and a == b
|
||||
|
||||
|
||||
def collect(records, registry):
|
||||
"""(kind, slug) -> info for every place with a page: PAGE_MIN or more trails.
|
||||
|
||||
An info holds kind, slug, key ("<kind>/<slug>"), name, label, prep, where, box,
|
||||
records, path and title_name. A wilderness area or a mountain range that holds exactly the
|
||||
trails of a park of much the same name gets no page: one page for the one set, under
|
||||
the park. The registry normally already leaves such a place out; the builder stays safe."""
|
||||
mem = membership(records, registry)
|
||||
out = {}
|
||||
for (kind, slug), recs in mem.items():
|
||||
if len(recs) < PAGE_MIN:
|
||||
continue
|
||||
e = registry[(kind, slug)]
|
||||
info = {"kind": kind, "slug": slug, "key": f"{kind}/{slug}", "name": e.get("name", slug),
|
||||
"label": label_of(e), "prep": prep_of(e),
|
||||
"where": list(e.get("where") or []), "box": e.get("box"), "records": recs,
|
||||
"path": path(kind, slug)}
|
||||
info["title_name"] = title_name(info)
|
||||
out[(kind, slug)] = info
|
||||
parks = [i for i in out.values() if i["kind"] == "park"]
|
||||
for key, info in list(out.items()):
|
||||
if info["kind"] not in ("wilderness", "range"):
|
||||
continue
|
||||
ids = {r["id"] for r in info["records"]}
|
||||
same = _doubled if info["kind"] == "wilderness" else _same_stem
|
||||
if any({r["id"] for r in p["records"]} == ids and same(p["name"], info["name"])
|
||||
for p in parks):
|
||||
del out[key]
|
||||
return out
|
||||
|
||||
|
||||
def _infos(infos):
|
||||
return list(infos.values()) if isinstance(infos, dict) else list(infos or ())
|
||||
|
||||
|
||||
def _by_kind_then_name(infos):
|
||||
return sorted(infos, key=lambda i: (KIND_ORDER.get(i["kind"], 99), i["name"].lower()))
|
||||
|
||||
|
||||
def in_state(infos, state_key):
|
||||
"""The places with a page that lie in one state or province (state_key as in
|
||||
olt/facets.py, "US-WY"), by kind then name."""
|
||||
want = _state_key(state_key)
|
||||
return _by_kind_then_name([i for i in _infos(infos)
|
||||
if want in {_state_key(c) for c in i.get("where") or []}])
|
||||
|
||||
|
||||
def of_record(rec, infos):
|
||||
"""The places of one trail that have a page, by kind then name. A parent range is
|
||||
among them: the infos' records are already closed over `within`."""
|
||||
return _by_kind_then_name([i for i in _infos(infos)
|
||||
if any(r["id"] == rec["id"] for r in i["records"])])
|
||||
+190
-54
@@ -5,8 +5,9 @@ Every page lists trails with home.results(), the same rows the home page shows.
|
||||
The section is called Places; its pages keep their /regions/ URLs.
|
||||
"""
|
||||
import collections
|
||||
from dataclasses import dataclass
|
||||
|
||||
from . import bounds, browse, common, facets, home, leftout, summary, words
|
||||
from . import bounds, browse, common, facets, home, leftout, places, summary, words
|
||||
from .markup import Markup, esc
|
||||
|
||||
|
||||
@@ -22,7 +23,8 @@ def collect_regions(records):
|
||||
continue
|
||||
slug = key.lower()
|
||||
country, code = key.split("-", 1)
|
||||
info = by_slug.setdefault(slug, {"key": key, "code": code, "country": country,
|
||||
info = by_slug.setdefault(slug, {"kind": "state", "key": key, "code": code,
|
||||
"country": country,
|
||||
"name": facets.place_name(key),
|
||||
"group": facets.GROUP_OF.get(key, ""), "records": []})
|
||||
if all(x["id"] != r["id"] for x in info["records"]):
|
||||
@@ -145,9 +147,25 @@ def lists_here(recs, records):
|
||||
return parts
|
||||
|
||||
|
||||
def regions_index_page(records, site):
|
||||
"""(title, description, body) for /regions/: the Places hub."""
|
||||
def place_links_for(state_key, infos):
|
||||
"""The nav a state page carries to the parks, ranges and wilderness areas in it
|
||||
that have a page, each with its exact count; empty when there are none. infos:
|
||||
olt/places.py collect. state_key as in olt/facets.py ("US-CO")."""
|
||||
here = places.in_state(infos, state_key)
|
||||
if not here:
|
||||
return Markup("")
|
||||
name = facets.place_name(state_key)
|
||||
links = " · ".join(f'<a href="{esc(i["path"])}">{esc(i["name"])}</a> ({len(i["records"])})'
|
||||
for i in here)
|
||||
return Markup(f'<nav class="region-nav" aria-label="Parks, ranges and wilderness in {esc(name)}">'
|
||||
f'Parks, ranges and wilderness in {esc(name)}, and how many trails in each: {links}</nav>')
|
||||
|
||||
|
||||
def regions_index_page(records, site, infos=()):
|
||||
"""(title, description, body) for /regions/: the Places hub. infos: the places with
|
||||
a page (olt/places.py collect); each kind that has any gets a section of its own."""
|
||||
by_slug, across = collect_regions(records)
|
||||
place_infos = list(infos.values()) if isinstance(infos, dict) else list(infos or ())
|
||||
blocks = ""
|
||||
jump = []
|
||||
for g, name, keys in facets.PLACE_GROUPS:
|
||||
@@ -174,6 +192,21 @@ def regions_index_page(records, site):
|
||||
<p class="places__sum">{_plural(len(across))} that {"crosses" if len(across) == 1 else "cross"} the whole country rather than one province: {links}.
|
||||
{"It is" if len(across) == 1 else "They are"} counted in every Canadian group, and on no single province’s page.</p>
|
||||
</section>"""
|
||||
for kind in places.KINDS.values():
|
||||
mine = sorted((i for i in place_infos if i["kind"] == kind.key), key=lambda i: i["name"])
|
||||
if not mine:
|
||||
continue
|
||||
rows = "".join(
|
||||
f'<li><a href="{esc(i["path"])}">{esc(i["name"])}</a>'
|
||||
f'<span class="places__n">{_plural(len(i["records"]))}</span></li>'
|
||||
for i in mine)
|
||||
jump.append(f'<li><a href="#{esc(kind.segment)}">{esc(kind.hub_title)}<span class="lists-row__n">{len(mine)}</span></a></li>')
|
||||
blocks += f"""<section class="places__group" aria-labelledby="{esc(kind.segment)}">
|
||||
<h2 id="{esc(kind.segment)}">{esc(kind.hub_title)}</h2>
|
||||
<ul class="places__list">{rows}</ul>
|
||||
</section>"""
|
||||
lede_more = (" Parks, mountain ranges and wilderness areas with three or more trails have pages too."
|
||||
if place_infos else "")
|
||||
none = empty_places(records)
|
||||
foot = ""
|
||||
if none:
|
||||
@@ -184,9 +217,9 @@ def regions_index_page(records, site):
|
||||
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
|
||||
<div class="titleblock__text"><h1>Places</h1>
|
||||
<p class="page-head__lede">The {len(records)} trails by state and province, grouped into parts of the
|
||||
United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one’s page.</p>
|
||||
United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one’s page.{lede_more}</p>
|
||||
</div></header>
|
||||
<nav class="lists-row" aria-label="Jump to a part of the country"><ul>{"".join(jump)}</ul></nav></div></div>
|
||||
<nav class="lists-row" aria-label="Jump to a part of the country{" or a kind of place" if place_infos else ""}"><ul>{"".join(jump)}</ul></nav></div></div>
|
||||
<div class="container section places">{blocks}</div>{foot}"""
|
||||
description = (f"Where the {len(records)} long trails and routes are: {n_us} in the United States and {n_ca} in Canada, "
|
||||
f"by state and province, with the number in each.")
|
||||
@@ -244,64 +277,83 @@ def group_page(g, records, site):
|
||||
return title, desc, Markup(body), home.has_overview_map(recs), recs
|
||||
|
||||
|
||||
def region_page(slug, records, site, facet_pages=()):
|
||||
"""(title, description, body, needs_map) for /regions/<slug>/: the trails in one state or province.
|
||||
@dataclass(frozen=True)
|
||||
class PageKind:
|
||||
"""What one kind of place page needs that another does not: its kicker, crumbs and
|
||||
lede, its title and description, the ground its map opens on, and its navs. The
|
||||
page itself (place_page) is shared: a state, a park, a range and a wilderness
|
||||
area are all a kind plus its info, and states are one kind (STATE below, the
|
||||
park, range and wilderness kinds in olt/placepages.py).
|
||||
|
||||
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"]
|
||||
key = info["key"]
|
||||
group = info["group"]
|
||||
group_name = facets.GROUP_NAME.get(group, "")
|
||||
country = words.COUNTRIES[info["country"]]
|
||||
n_gpx = _gpx_count(recs)
|
||||
kicker(info) -> str: plain text. crumbs(info) -> HTML <li>s before this page.
|
||||
lede(info, recs, n_gpx) -> HTML. where: the finder Where filter's scope
|
||||
(home.finder_form; "" for none). wholly: open with the trails wholly in the
|
||||
place first. facts_place(info) -> (name, state keys) for summary.facts and for
|
||||
that test (no keys: no whole-trail figure is given as the place's).
|
||||
title_options(info, recs, site) -> titles, fullest first, for common.fit_title.
|
||||
description(info, recs) -> str. box(info) -> [west, south, east, north] or None.
|
||||
nav(info, records, recs, facet_pages) -> HTML after the rows and map.
|
||||
in_name(info) -> str, where present: the name as it reads after a verb ("the Wind
|
||||
River Range"); the plain name where the kind leaves it out. phrase(info) -> str,
|
||||
where present: the preposition and the name ("on the Colorado Plateau"); where the
|
||||
kind leaves it out, "in" and in_name."""
|
||||
kicker: object
|
||||
crumbs: object
|
||||
lede: object
|
||||
where: str
|
||||
wholly: bool
|
||||
facts_place: object
|
||||
title_options: object
|
||||
description: object
|
||||
box: object
|
||||
nav: object
|
||||
in_name: object = None
|
||||
phrase: object = None
|
||||
always_filters: bool = False # the filter bar whatever the number of trails
|
||||
|
||||
|
||||
def _state_kicker(info):
|
||||
group_name = facets.GROUP_NAME.get(info["group"], "")
|
||||
return (group_name + " · " if group_name else "") + words.COUNTRIES[info["country"]]
|
||||
|
||||
|
||||
def _state_crumbs(info):
|
||||
crumbs = '<li><a href="/regions/">Places</a></li>'
|
||||
if group:
|
||||
crumbs += f'<li><a href="{esc(group_path(group))}">{esc(group_name)}</a></li>'
|
||||
siblings = []
|
||||
if group:
|
||||
_, _, keys = next(x for x in facets.PLACE_GROUPS if x[0] == group)
|
||||
for k in sorted(keys, key=facets.place_name):
|
||||
if k != key and k.lower() in by_slug:
|
||||
siblings.append(f'<a href="{esc(facets.place_path(k))}">{esc(facets.place_name(k))}</a>')
|
||||
nav = (f'<nav class="region-nav" aria-label="Elsewhere in {esc(group_name)}">Elsewhere in {esc(group_name)}: '
|
||||
f'{" · ".join(siblings)}</nav>') if siblings else ""
|
||||
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>")
|
||||
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">
|
||||
<p class="kicker">{esc(group_name + " · " if group_name else "")}{esc(country)}</p>
|
||||
<h1>{esc(info["name"])}</h1>
|
||||
<p class="page-head__lede">{_plural(len(recs))} in {esc(info["name"])}, {n_gpx} with a GPX here.</p>
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
{home.browse_view(home.listing(recs, top=2, where="", wholly=wholly_in(recs, [key])), home.overview_map(recs, f"Map of the trails in {info['name']}", place=bounds.place_box(key)),
|
||||
about=f"{summary.facts(recs, records, place=(info['name'], [key]))}{summary.details(recs)}",
|
||||
about_title=f"About the trails in {info['name']}")}
|
||||
{nav}
|
||||
</div>"""
|
||||
if info["group"]:
|
||||
crumbs += (f'<li><a href="{esc(group_path(info["group"]))}">'
|
||||
f'{esc(facets.GROUP_NAME.get(info["group"], ""))}</a></li>')
|
||||
return crumbs
|
||||
|
||||
|
||||
def _state_lede(info, recs, n_gpx):
|
||||
return f"{_plural(len(recs))} in {esc(info['name'])}, {n_gpx} with a GPX here."
|
||||
|
||||
|
||||
def _state_facts_place(info):
|
||||
return (info["name"], [info["key"]])
|
||||
|
||||
|
||||
def _state_title_options(info, recs, site):
|
||||
name = info["name"]
|
||||
routes = sum(1 for r in recs if common.is_route(r))
|
||||
mixed = 0 < routes < len(recs)
|
||||
options = []
|
||||
if mixed:
|
||||
if 0 < routes < len(recs):
|
||||
options.append(f"Long Trails in {name}: {_plural(len(recs) - routes, 'Trail')} and {_plural(routes, 'Route')}")
|
||||
options.append(f"Long Trails in {name}: {len(recs)} Trails and Routes")
|
||||
else:
|
||||
options.append(f"Long Trails in {name}: {_plural(len(recs), 'Route' if routes else 'Trail')}")
|
||||
options.append(f"Long Trails in {name}")
|
||||
title = common.fit_title(options, site)
|
||||
return options
|
||||
|
||||
|
||||
def _state_description(info, recs):
|
||||
name, key = info["name"], info["key"]
|
||||
country = words.COUNTRIES[info["country"]]
|
||||
n_gpx = _gpx_count(recs)
|
||||
routes = sum(1 for r in recs if common.is_route(r))
|
||||
by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"]))
|
||||
shortest, longest = by_length[0], by_length[-1]
|
||||
what = _plural(len(recs), "trail") + (" and routes" if mixed else "")
|
||||
what = _plural(len(recs), "trail") + (" and routes" if 0 < routes < len(recs) else "")
|
||||
if routes == len(recs):
|
||||
what = _plural(len(recs), "route")
|
||||
gpx = f" {_with_gpx(n_gpx, len(recs))[:1].upper()}{_with_gpx(n_gpx, len(recs))[1:]}." if n_gpx else ""
|
||||
@@ -310,8 +362,92 @@ def region_page(slug, records, site, facet_pages=()):
|
||||
else:
|
||||
first = (f"{what[:1].upper() + what[1:]} in {name}, {country}, from {common.plain_name(shortest)}, {trail_miles(shortest, [key])}, "
|
||||
f"to {common.plain_name(longest)}, {trail_miles(longest, [key])}.")
|
||||
desc = _fit([first + gpx, first, f"{what[:1].upper() + what[1:]} in {name}, {country}.{gpx}"])
|
||||
return title, desc, Markup(body), home.has_overview_map(recs)
|
||||
return _fit([first + gpx, first, f"{what[:1].upper() + what[1:]} in {name}, {country}.{gpx}"])
|
||||
|
||||
|
||||
def _lists_nav(name, recs, records, phrase=None):
|
||||
"""The nav of ready-made lists holding some of these trails, shared by the kinds.
|
||||
phrase is "in <name>" unless the place has its own preposition."""
|
||||
held = lists_here(recs, records)
|
||||
if not held:
|
||||
return ""
|
||||
phrase = phrase or f"in {name}"
|
||||
return (f'<nav class="region-nav" aria-label="Lists with trails {esc(phrase)}">'
|
||||
f'Lists with trails {esc(phrase)}, and how many here: {" · ".join(held)}</nav>')
|
||||
|
||||
|
||||
def _facet_nav(name, facet_pages, phrase=None):
|
||||
"""The nav of this place's pages of one kind of trail, shared by the kinds."""
|
||||
if not facet_pages:
|
||||
return ""
|
||||
phrase = phrase or f"in {name}"
|
||||
return (f'<nav class="region-nav" aria-label="Kinds of trail {esc(phrase)}">'
|
||||
f'More {esc(phrase)}: '
|
||||
+ " · ".join(f'<a href="{esc(path)}">{esc(label)}</a> ({n})' for label, path, n in facet_pages)
|
||||
+ "</nav>")
|
||||
|
||||
|
||||
def _state_nav(info, records, recs, facet_pages):
|
||||
key, group = info["key"], info["group"]
|
||||
group_name = facets.GROUP_NAME.get(group, "")
|
||||
by_slug, _ = collect_regions(records)
|
||||
siblings = []
|
||||
if group:
|
||||
_, _, keys = next(x for x in facets.PLACE_GROUPS if x[0] == group)
|
||||
for k in sorted(keys, key=facets.place_name):
|
||||
if k != key and k.lower() in by_slug:
|
||||
siblings.append(f'<a href="{esc(facets.place_path(k))}">{esc(facets.place_name(k))}</a>')
|
||||
nav = (f'<nav class="region-nav" aria-label="Elsewhere in {esc(group_name)}">Elsewhere in {esc(group_name)}: '
|
||||
f'{" · ".join(siblings)}</nav>') if siblings else ""
|
||||
return nav + _lists_nav(info["name"], recs, records) + _facet_nav(info["name"], facet_pages)
|
||||
|
||||
|
||||
STATE = PageKind(kicker=_state_kicker, crumbs=_state_crumbs, lede=_state_lede, where="",
|
||||
wholly=True, facts_place=_state_facts_place, title_options=_state_title_options,
|
||||
description=_state_description, box=lambda info: bounds.place_box(info["key"]),
|
||||
nav=_state_nav)
|
||||
|
||||
|
||||
def place_page(info, records, site, kind, *, facet_pages=(), place_links=""):
|
||||
"""(title, description, body, needs_map) for the page of one place of one kind: a
|
||||
state or province, a park, a mountain range or a wilderness area. info holds at
|
||||
least name and records; kind (a PageKind) holds the rest.
|
||||
|
||||
facet_pages: [(label, path, how many)] for this place's pages of one kind of
|
||||
trail (olt/placefacets.py). place_links: HTML put after the kind's navs (on a
|
||||
state page, the parks, ranges and wilderness areas in the state)."""
|
||||
recs = info["records"]
|
||||
n_gpx = _gpx_count(recs)
|
||||
crumbs = kind.crumbs(info)
|
||||
nav = kind.nav(info, records, recs, facet_pages)
|
||||
place = kind.facts_place(info)
|
||||
wholly = wholly_in(recs, place[1]) if kind.wholly else None
|
||||
in_name = kind.in_name(info) if kind.in_name else info["name"]
|
||||
phrase = kind.phrase(info) if kind.phrase else f"in {in_name}"
|
||||
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">
|
||||
<p class="kicker">{esc(kind.kicker(info))}</p>
|
||||
<h1>{esc(info["name"])}</h1>
|
||||
<p class="page-head__lede">{kind.lede(info, recs, n_gpx)}</p>
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
{home.browse_view(home.listing(recs, top=2, where=kind.where, wholly=wholly, always=kind.always_filters), home.overview_map(recs, f"Map of the trails {phrase}", place=kind.box(info)),
|
||||
about=f"{summary.facts(recs, records, place=place)}{summary.details(recs)}",
|
||||
about_title=f"About the trails {phrase}")}
|
||||
{nav}{place_links}
|
||||
</div>"""
|
||||
title = common.fit_title(kind.title_options(info, recs, site), site)
|
||||
return title, kind.description(info, recs), Markup(body), home.has_overview_map(recs)
|
||||
|
||||
|
||||
def region_page(slug, records, site, facet_pages=(), place_links=""):
|
||||
"""(title, description, body, needs_map) for /regions/<slug>/: the trails in one
|
||||
state or province, built through place_page with the STATE kind."""
|
||||
by_slug, _ = collect_regions(records)
|
||||
return place_page(by_slug[slug], records, site, STATE,
|
||||
facet_pages=facet_pages, place_links=place_links)
|
||||
|
||||
|
||||
def route_guides(rec):
|
||||
|
||||
+49
-9
@@ -5,7 +5,8 @@ A row's words come in four tiers, strongest first, so that the list can put the
|
||||
0 name the name, its common name, its abbreviation and its id
|
||||
1 author who made a route
|
||||
2 places the full names of the states and provinces it lies in, the countries, the place it
|
||||
starts and the place it ends, and the land unit or managing body its record names
|
||||
starts and the place it ends, the land unit or managing body its record names, and
|
||||
the parks, mountain ranges and wilderness areas it is in (place_names)
|
||||
3 summary the trail's summary
|
||||
|
||||
Each tier is folded (fold) and written once per word (the summary's words of fewer than three letters are
|
||||
@@ -37,9 +38,47 @@ def fold(text):
|
||||
return _NOT_WORD.sub(" ", _APOSTROPHES.sub("", text)).strip()
|
||||
|
||||
|
||||
def place_names(rec):
|
||||
# {record id: [place name]} for every park, range and wilderness area a trail is in
|
||||
# (olt/places.py membership, parents included), set by pages.render_site through
|
||||
# use_place_names: typing "wind river" then finds the trails of the range, whether
|
||||
# or not the place has a page. Like home's author links, it is build state.
|
||||
_PLACE_NAMES = {}
|
||||
|
||||
|
||||
def use_place_names(mapping):
|
||||
_PLACE_NAMES.clear()
|
||||
_PLACE_NAMES.update({k: list(v) for k, v in (mapping or {}).items()})
|
||||
|
||||
|
||||
def _names_from_infos(rec, infos):
|
||||
"""The names of a record's places out of infos: the infos of places.collect (a dict
|
||||
keyed (kind, slug), or a list of them; their records already include the parents),
|
||||
or a registry in the same keying, whose names the record's [[place]] tables pick
|
||||
out, with every `within` parent. [] when infos is neither."""
|
||||
if isinstance(infos, dict) and infos and all(isinstance(k, tuple) for k in infos):
|
||||
if any(isinstance(v, dict) and "records" in v for v in infos.values()):
|
||||
return [v["name"] for v in infos.values()
|
||||
if any(r["id"] == rec["id"] for r in v.get("records") or [])]
|
||||
out, stack = [], [(p.get("kind"), p.get("slug")) for p in rec.get("place") or []
|
||||
if isinstance(p, dict)]
|
||||
seen = set()
|
||||
while stack:
|
||||
key = stack.pop(0)
|
||||
if key in seen or key not in infos:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(infos[key].get("name", ""))
|
||||
stack += [("range", s) for s in infos[key].get("within") or []]
|
||||
return out
|
||||
return [i["name"] for i in infos or ()
|
||||
if isinstance(i, dict) and any(r["id"] == rec["id"] for r in i.get("records") or [])]
|
||||
|
||||
|
||||
def place_names(rec, infos=()):
|
||||
"""The names of the places a record carries: states, provinces and countries in full, where it
|
||||
starts and ends, and the land unit or body of its designation."""
|
||||
starts and ends, the land unit or body of its designation, and the parks, mountain
|
||||
ranges and wilderness areas it is in (from infos where given, else the names the
|
||||
build set with use_place_names)."""
|
||||
names = [facets.place_name(k) for k in facets.place_keys(rec)]
|
||||
names += [words.COUNTRIES.get(c, c) for c in common.countries(rec)]
|
||||
h = hike.table(rec)
|
||||
@@ -47,24 +86,25 @@ def place_names(rec):
|
||||
designation = rec.get("designation", "")
|
||||
if designation and not _NO_BODY.match(designation):
|
||||
names.append(designation)
|
||||
names += _names_from_infos(rec, infos) if infos else _PLACE_NAMES.get(rec["id"], [])
|
||||
return [n for n in names if isinstance(n, str) and n.strip()]
|
||||
|
||||
|
||||
def tier_texts(rec):
|
||||
def tier_texts(rec, infos=()):
|
||||
"""The four texts of a record, unfolded."""
|
||||
return [
|
||||
" ".join([rec["name"], rec.get("common_name", ""), rec.get("short_name", ""), rec["id"]]),
|
||||
facets.author(rec),
|
||||
" ".join(place_names(rec)),
|
||||
" ".join(place_names(rec, infos)),
|
||||
hike.table(rec).get("summary", ""),
|
||||
]
|
||||
|
||||
|
||||
def tiers(rec):
|
||||
def tiers(rec, infos=()):
|
||||
"""The four tiers as lists of words, each word in the strongest tier that has it."""
|
||||
seen = set()
|
||||
out = []
|
||||
for i, text in enumerate(tier_texts(rec)):
|
||||
for i, text in enumerate(tier_texts(rec, infos)):
|
||||
mine = []
|
||||
for word in fold(text).split():
|
||||
if i == SUMMARY and len(word) < SUMMARY_MIN:
|
||||
@@ -76,6 +116,6 @@ def tiers(rec):
|
||||
return out
|
||||
|
||||
|
||||
def attribute(rec):
|
||||
def attribute(rec, infos=()):
|
||||
"""The value of a row's data-search: the tiers' words, tiers joined with "|"."""
|
||||
return "|".join(" ".join(t) for t in tiers(rec))
|
||||
return "|".join(" ".join(t) for t in tiers(rec, infos))
|
||||
+51
-11
@@ -9,7 +9,7 @@ import os
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
from . import browse, common, elevation, facets, hike, regions, related, seo, sketch, words
|
||||
from . import browse, common, elevation, facets, hike, places, regions, related, seo, sketch, words
|
||||
from .layout import OUTDOOR_STYLE
|
||||
from .markup import Markup, esc
|
||||
|
||||
@@ -83,6 +83,27 @@ def region_names(rec):
|
||||
return Markup((", " if len(keys) <= 3 else " ").join(parts))
|
||||
|
||||
|
||||
def place_links(rec, infos):
|
||||
"""One link per park, range or wilderness area of this trail that has a page
|
||||
(olt/places.py collect), for the glance beside its states; "" when none has."""
|
||||
mine = places.of_record(rec, infos)
|
||||
if not mine:
|
||||
return Markup("")
|
||||
return Markup(", ".join(f'<a href="{esc(i["path"])}">{esc(i["name"])}</a>' for i in mine))
|
||||
|
||||
|
||||
def places_nav(rec, infos):
|
||||
"""The same place links as the glance's Where row, as a line at the foot of the page. On a
|
||||
phone the glance shows only its first facts until "All the facts" is tapped, and the Where
|
||||
row is not among them; this line is shown there (style.css, .trail-places) so the links are
|
||||
on the page without a tap. "" when the trail is in no place that has a page."""
|
||||
links = place_links(rec, infos)
|
||||
if not links:
|
||||
return ""
|
||||
return Markup(f'<nav class="region-nav trail-places" aria-label="Parks, ranges and wilderness areas">'
|
||||
f'Parks, ranges and wilderness areas: {links}</nav>')
|
||||
|
||||
|
||||
_ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)")
|
||||
|
||||
|
||||
@@ -623,11 +644,12 @@ def time_note(rec, records):
|
||||
PERMITS = "Permits"
|
||||
|
||||
|
||||
def glance(rec, records=None):
|
||||
def glance(rec, records=None, place_infos=()):
|
||||
"""The hiker's facts at a glance, under the attribute names every page uses.
|
||||
|
||||
records: every trail, so that terrain, shape, time and length link to the
|
||||
lists they put the trail in (left out when None)."""
|
||||
lists they put the trail in (left out when None). place_infos: the places with
|
||||
a page (olt/places.py collect); the trail's own are linked in the Where row."""
|
||||
h = hike.table(rec)
|
||||
# The length leads, set large. A built or a whole-system figure under it is a line across the
|
||||
# whole panel, so the row is as wide as the panel.
|
||||
@@ -683,7 +705,11 @@ def glance(rec, records=None):
|
||||
if h.get("permit"):
|
||||
rows.append(glance_row(PERMITS, common.sentence(h["permit"]), wide=True))
|
||||
country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec))
|
||||
rows.append(glance_row(facets.WHERE, Markup(f'{region_names(rec)}, {esc(country)}'), wide=True))
|
||||
where_value = Markup(f'{region_names(rec)}, {esc(country)}')
|
||||
links = place_links(rec, place_infos)
|
||||
if links:
|
||||
where_value = Markup(f"{where_value}<br>{links}")
|
||||
rows.append(glance_row(facets.WHERE, where_value, wide=True))
|
||||
status = facets.gpx(rec)
|
||||
if facets.gpx_here(rec):
|
||||
text = facets.gpx_status_text(rec)
|
||||
@@ -1803,11 +1829,12 @@ def nearest_length(rec, other):
|
||||
RELATED_WHY = {"name": "same name", "named": "named here", "names": "mentions this"}
|
||||
|
||||
|
||||
def onward(rec, records):
|
||||
def onward(rec, records, place_infos=()):
|
||||
"""Ways onward at the foot of the page, all worked out from the records (olt/related.py):
|
||||
trails tied to this one by name or by what the descriptions say; other trails in the
|
||||
same state or province (up to three of them), the closest in length first; trails like this one in length, terrain
|
||||
and shape; and for a route, other routes by the same author."""
|
||||
same state or province (up to three of them), the closest in length first; other trails
|
||||
in the same park, range or wilderness area that has a page (place_infos); trails like
|
||||
this one in length, terrain and shape; and for a route, other routes by the same author."""
|
||||
if not records:
|
||||
return ""
|
||||
others = [r for r in records if r["id"] != rec["id"]]
|
||||
@@ -1827,6 +1854,16 @@ def onward(rec, records):
|
||||
more = (facets.place_path(key), f"All {len(here) + 1} trails in {name}") if len(here) > ONWARD_MAX else \
|
||||
(facets.place_path(key), f"{name} on the map")
|
||||
parts.append(_onward_list(f"More in {name}", here, more[0], more[1], f"onward-{key.lower()}"))
|
||||
for info in places.of_record(rec, place_infos)[:3]:
|
||||
here = sorted((r for r in info["records"] if r["id"] != rec["id"]),
|
||||
key=lambda r: nearest_length(rec, r))
|
||||
if not here:
|
||||
continue
|
||||
where = places.in_name(info)
|
||||
more = (info["path"], f"All {len(info['records'])} trails in {where}") if len(here) > ONWARD_MAX else \
|
||||
(info["path"], f"{info['name']} on the map")
|
||||
parts.append(_onward_list(f"More in {where}", here, more[0], more[1],
|
||||
f"onward-{info['kind']}-{info['slug']}"))
|
||||
like = related.similar_to(rec, records)
|
||||
if like:
|
||||
def alike(r):
|
||||
@@ -1844,9 +1881,11 @@ def onward(rec, records):
|
||||
f'<div class="onward__grid">{"".join(parts)}</div></nav>')
|
||||
|
||||
|
||||
def render(rec, site, records=None, author_links=None):
|
||||
def render(rec, site, records=None, author_links=None, place_infos=()):
|
||||
"""Return (title, description, body HTML, needs_map) for one trail.
|
||||
records: every trail, for the ways onward at the foot (left out when None)."""
|
||||
records: every trail, for the ways onward at the foot (left out when None).
|
||||
place_infos: the places with a page (olt/places.py collect), linked in the
|
||||
glance and the ways onward."""
|
||||
has_track = common.has_line(rec)
|
||||
sketch_points = hike.sketch_points(rec) if not has_track else []
|
||||
has_map = has_track or bool(sketch_points)
|
||||
@@ -1854,7 +1893,7 @@ def render(rec, site, records=None, author_links=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)
|
||||
side = f'<div class="detail__side">{glance(rec, records)}{aside_html}{map_credit(rec)}</div>'
|
||||
side = f'<div class="detail__side">{glance(rec, records, place_infos)}{aside_html}{map_credit(rec)}</div>'
|
||||
body = f"""{page_head(rec, author_links)}
|
||||
<div class="container detail{"" if aside else " detail--no-aside"}{"" if has_map else " detail--no-map"}{" detail--with-profile" if profile else ""}">
|
||||
{strip(rec)}
|
||||
@@ -1864,7 +1903,8 @@ def render(rec, site, records=None, author_links=None):
|
||||
{profile}
|
||||
</div>
|
||||
<div class="container trail-more">
|
||||
{onward(rec, records)}
|
||||
{places_nav(rec, place_infos)}
|
||||
{onward(rec, records, place_infos)}
|
||||
{page_foot(rec, site)}
|
||||
{about_data(rec, site, author_links)}
|
||||
{history_section(rec)}
|
||||
|
||||
Reference in new issue
Block a user