diff --git a/SOURCES.md b/SOURCES.md index 371f49e..a61e580 100644 --- a/SOURCES.md +++ b/SOURCES.md @@ -62,6 +62,38 @@ Terms found: none. No route creator's page read on 2026-11-10 states a licence f Page: the creator's or publisher's own page for the guide, given in each record's first `[[guide]]` and quoted in `route.creator_words_url` where the creator's words are quoted. +## National Park Service park boundaries (public domain) + +Used for: the outlines behind the park pages. `tools/place_trails.py` measures each trail's track against the Land Resources Division boundary service and writes the trail's park membership to its record and to `places.toml`. The outlines themselves are not in this repository; they are downloaded to a cache outside it. + +Quoted terms: "The data are in the public domain, and may be re-used without restriction." + +Page: https://irma.nps.gov/DataStore/Reference/Profile/2224545 (read 2026-11-20). United States federal government work is public domain in the United States under 17 U.S.C. 105 (see "United States federal agencies" above). Credit: National Park Service, Land Resources Division. + +## Wilderness Connect wilderness boundaries (public domain) + +Used for: the outlines behind the wilderness area pages, all four federal agencies in one file. `tools/place_trails.py` measures each trail's track against them; the outlines are cached outside this repository. + +Quoted terms: "This data is available for public use of any kind. Crediting Wilderness Connect is requested." + +Page: https://wilderness.net/visit-wilderness/gis-gps.php (read 2026-11-20). Federal work, public domain. The credit the page requests is given here: Wilderness Connect, University of Montana (wilderness.net). + +## Canadian Protected and Conserved Areas Database (Open Government Licence, Canada) + +Used for: the outlines of Canadian national parks and of British Columbia and Alberta provincial parks, measured by `tools/place_trails.py` and cached outside this repository. + +Quoted terms: "Copy, modify, publish, translate, adapt, distribute or otherwise use the Information in any medium, mode or format for any lawful purpose." + +Page: https://open.canada.ca/data/dataset/6c343726-1e92-451a-876a-76e17d398a1c and the licence at https://open.canada.ca/en/open-government-licence-canada (read 2026-11-20). Credit: Environment and Climate Change Canada, CPCAD. Contains information licensed under the Open Government Licence – Canada. + +## GMBA Mountain Inventory v2 (CC BY 4.0) + +Used for: the outlines behind the mountain range pages, the allow-listed ranges only (`tools/place_allowlist.toml`), measured by `tools/place_trails.py` and cached outside this repository. + +Quoted terms: the inventory's licence reads "CC BY 4.0". + +Page: https://www.earthenv.org/mountains and https://doi.org/10.48601/earthenv-t9k2-1407 (read 2026-11-20). Full text: LICENSES/CC-BY-4.0.txt. Credit required: GMBA Mountain Inventory v2 (Snethlage et al. 2022), via EarthEnv. + ## Every record's source diff --git a/web/olt/layout.py b/web/olt/layout.py index 2f41d58..57fe991 100644 --- a/web/olt/layout.py +++ b/web/olt/layout.py @@ -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 diff --git a/web/olt/pages.py b/web/olt/pages.py index 197cc40..dbd4241 100644 --- a/web/olt/pages.py +++ b/web/olt/pages.py @@ -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 /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) diff --git a/web/olt/placepages.py b/web/olt/placepages.py new file mode 100644 index 0000000..72aac44 --- /dev/null +++ b/web/olt/placepages.py @@ -0,0 +1,96 @@ +"""Pages for national parks, mountain ranges and wilderness areas: + /parks//, /ranges//, /wilderness// + +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 _title_place(info): + """The name in a page's title: _in_name with its one state spelled out for a + range or wilderness area (places.title_name), "the Wind River Range, Wyoming".""" + text = places.title_name(info) + if info["kind"] in ("range", "wilderness") and not text.lower().startswith("the "): + return f"the {text}" + return text + + +def _kicker(info): + noun = places.KINDS[info["kind"]].noun + names = places.state_names(info) + return f"{noun} · {words.join_names(names)}" if names else noun + + +def _crumbs(info): + return '
  • Trails
  • Places
  • ' + + +def _lede(info, recs, n_gpx): + return f"{regions._plural(len(recs))} in {esc(_in_name(info))}, {n_gpx} with a GPX here." + + +def _title_options(info, recs, site): + base = f"Long Hikes in {_title_place(info)}" + return [f"{base}: {regions._plural(len(recs), 'Trail')}", base] + + +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} in {_title_place(info)}, 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} in {_title_place(info)}.{gpx}"]) + + +def _nav(info, records, recs, facet_pages): + return (regions._lists_nav(_in_name(info), recs, records) + + regions._facet_nav(_in_name(info), facet_pages)) + + +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) + + +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 diff --git a/web/olt/places.py b/web/olt/places.py new file mode 100644 index 0000000..a5c31fd --- /dev/null +++ b/web/olt/places.py @@ -0,0 +1,195 @@ +"""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// + 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/, /ranges/wind-river-range/, /wilderness//.""" + 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 []] + + +def in_name(info): + """The name as it reads after "in": a range or a wilderness area takes "the" + ("in the Wind River Range"), a park does not ("in Yosemite National Park").""" + name = info["name"] + if info.get("kind") in ("range", "wilderness") and not name.lower().startswith("the "): + return f"the {name}" + return 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"), and with no state when it spans several.""" + name = info["name"] + if info.get("kind") == "park": + return name + names = state_names(info) + return f"{name}, {names[0]}" if len(names) == 1 else 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) + + +def collect(records, registry): + """(kind, slug) -> info for every place with a page: PAGE_MIN or more trails. + + An info holds kind, slug, key ("/"), name, where, box, records, path + and title_name. A wilderness area that holds exactly the trails of a national 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 wilderness 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), + "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"] != "wilderness": + continue + ids = {r["id"] for r in info["records"]} + if any({r["id"] for r in p["records"]} == ids and _doubled(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"])]) diff --git a/web/olt/regions.py b/web/olt/regions.py index a9008be..125149c 100644 --- a/web/olt/regions.py +++ b/web/olt/regions.py @@ -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'{esc(i["name"])} ({len(i["records"])})' + for i in here) + return Markup(f'') + + +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,20 @@ def regions_index_page(records, site):

    {_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.

    """ + 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'
  • {esc(i["name"])}' + f'{_plural(len(i["records"]))}
  • ' + for i in mine) + blocks += f"""
    +

    {esc(kind.hub_title)}

    +
      {rows}
    +
    """ + 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,7 +216,7 @@ def regions_index_page(records, site): body = f"""

    Places

    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.

    + United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one’s page.{lede_more}

    {blocks}
    {foot}""" @@ -244,64 +276,79 @@ 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//: 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
  • 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 "in" ("the Wind + River Range"); the plain name where the kind leaves it out.""" + 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 + + +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 = '
  • Places
  • ' - if group: - crumbs += f'
  • {esc(group_name)}
  • ' - 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'{esc(facets.place_name(k))}') - nav = (f'') if siblings else "" - held = lists_here(recs, records) - nav += (f'') if held else "" - if facet_pages: - nav += (f'") - body = f"""
    - -
    -

    {esc(group_name + " · " if group_name else "")}{esc(country)}

    -

    {esc(info["name"])}

    -

    {_plural(len(recs))} in {esc(info["name"])}, {n_gpx} with a GPX here.

    -
    -
    -
    - {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} -
    """ + if info["group"]: + crumbs += (f'
  • ' + f'{esc(facets.GROUP_NAME.get(info["group"], ""))}
  • ') + 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 +357,88 @@ 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): + """The nav of ready-made lists holding some of these trails, shared by the kinds.""" + held = lists_here(recs, records) + if not held: + return "" + return (f'') + + +def _facet_nav(name, facet_pages): + """The nav of this place's pages of one kind of trail, shared by the kinds.""" + if not facet_pages: + return "" + return (f'") + + +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'{esc(facets.place_name(k))}') + nav = (f'') 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"] + body = f"""
    + +
    +

    {esc(kind.kicker(info))}

    +

    {esc(info["name"])}

    +

    {kind.lede(info, recs, n_gpx)}

    +
    +
    +
    + {home.browse_view(home.listing(recs, top=2, where=kind.where, wholly=wholly), home.overview_map(recs, f"Map of the trails in {in_name}", place=kind.box(info)), + about=f"{summary.facts(recs, records, place=place)}{summary.details(recs)}", + about_title=f"About the trails in {in_name}")} + {nav}{place_links} +
    """ + 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//: 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): diff --git a/web/olt/searchtext.py b/web/olt/searchtext.py index 22290a3..3d7a7ba 100644 --- a/web/olt/searchtext.py +++ b/web/olt/searchtext.py @@ -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)) diff --git a/web/olt/trail.py b/web/olt/trail.py index 37bb0e3..2560ec1 100644 --- a/web/olt/trail.py +++ b/web/olt/trail.py @@ -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,15 @@ 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'{esc(i["name"])}' for i in mine)) + + _ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)") @@ -611,11 +620,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. @@ -671,7 +681,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}
    {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) @@ -1789,11 +1803,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"]] @@ -1813,6 +1828,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): @@ -1830,9 +1855,11 @@ def onward(rec, records): f'
    {"".join(parts)}
    ') -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) @@ -1840,7 +1867,7 @@ def render(rec, site, records=None, author_links=None): aside_html = (f'') if aside else "" profile = elevation_figure(rec) - side = f'
    {glance(rec, records)}{aside_html}{map_credit(rec)}
    ' + side = f'
    {glance(rec, records, place_infos)}{aside_html}{map_credit(rec)}
    ' body = f"""{page_head(rec, author_links)}
    {strip(rec)} @@ -1850,7 +1877,7 @@ def render(rec, site, records=None, author_links=None): {profile}
    - {onward(rec, records)} + {onward(rec, records, place_infos)} {page_foot(rec, site)} {about_data(rec, site, author_links)} {history_section(rec)} diff --git a/web/tests/test_facets.py b/web/tests/test_facets.py index b1cbb9d..cd0f909 100644 --- a/web/tests/test_facets.py +++ b/web/tests/test_facets.py @@ -268,7 +268,9 @@ class BuiltVocabularyTest(unittest.TestCase): def browsing_pages(self): rels = ["index.html", "regions/index.html", "lists/index.html", "routes/index.html", "404.html"] - for d in ("regions", "lists"): + for d in ("regions", "lists", "parks", "ranges", "wilderness"): + if not os.path.isdir(os.path.join(OUT, d)): + continue for name in sorted(os.listdir(os.path.join(OUT, d))): if os.path.isfile(os.path.join(OUT, d, name, "index.html")): rels.append(f"{d}/{name}/index.html") diff --git a/web/tests/test_place_links.py b/web/tests/test_place_links.py new file mode 100644 index 0000000..b28bd63 --- /dev/null +++ b/web/tests/test_place_links.py @@ -0,0 +1,170 @@ +"""Links to the park, range and wilderness pages: the Places hub sections, the block +on a state page, the links on a trail page, and place names in search +(regions.regions_index_page, regions.place_links_for, trail.place_links, +searchtext.place_names). Fixtures only.""" +import hashlib +import json +import os +import re +import sys +import unittest + +WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +ROOT = os.path.dirname(WEB) +sys.path.insert(0, WEB) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from olt import home, placefacets, places, regions, searchtext, site, trail # noqa: E402 +from test_place_page import REGISTRY, rec, wind_records, yosemite_records # noqa: E402 +from test_state_pages_unchanged import GOLDEN, fixtures, normalise # noqa: E402 + +S = site.Site("Long Hikes", "T", repo_url="https://github.com/o/r") + + +def registry(entries=REGISTRY): + return {(e["kind"], e["slug"]): e for e in entries} + + +def infos(records): + return places.collect(records, registry()) + + +class HubTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.records = wind_records(4) + yosemite_records(3) + cls.infos = infos(cls.records) + + def test_the_hub_lists_each_kind_with_exact_counts_and_hides_empty_kinds(self): + _, _, body = regions.regions_index_page(self.records, S, infos=self.infos) + body = str(body) + self.assertIn(">Parks", body) + self.assertIn(">Mountain ranges", body) + self.assertNotIn(">Wilderness areas", body) + self.assertIn('Wind River Range' + '4 trails', body) + self.assertIn('Yosemite National Park' + '3 trails', body) + self.assertIn("Parks, mountain ranges and wilderness areas with three or more " + "trails have pages too.", re.sub(r"\s+", " ", body)) + + def test_the_hub_still_lists_every_state_group_as_before(self): + _, _, plain = regions.regions_index_page(self.records, S) + _, _, with_places = regions.regions_index_page(self.records, S, infos=self.infos) + stripped = re.sub(r'
    .*?
    ', + "", str(with_places), flags=re.S) + stripped = stripped.replace( + " Parks, mountain ranges and wilderness areas with three or more trails have pages too.", "") + self.assertEqual(stripped, str(plain)) + + +class StateLinkTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.records = fixtures() + # three Colorado fixtures in one range whose `where` is Colorado + cls.reg = {("range", "front-range"): { + "kind": "range", "slug": "front-range", "name": "Front Range", "where": ["CO"], + "source": "gmba-v2", "source_id": "1", "source_version": "2026-11-20", + "box": [-106.0, 38.0, -105.0, 41.0]}} + co = [r for r in cls.records if "CO" in r.get("regions", [])][:3] + for r in co: + r["place"] = [{"kind": "range", "slug": "front-range", "basis": "track", "km": 42.0}] + cls.infos = places.collect(cls.records, cls.reg) + + def test_a_state_page_links_to_the_places_in_the_state_with_exact_counts_and_nothing_else_changes(self): + block = regions.place_links_for("US-CO", self.infos) + self.assertIn('aria-label="Parks, ranges and wilderness in Colorado"', str(block)) + self.assertIn('Front Range (3)', str(block)) + plan = placefacets.plan(self.records) + facet_pages = [(placefacets.label(p["lst"]), p["path"], len(p["recs"])) + for p in placefacets.pages_by_place(plan).get("us-co", [])] + built = regions.region_page("us-co", self.records, S, facet_pages, place_links=block) + page = "\n".join(str(p) for p in built if isinstance(p, str) or hasattr(p, "__html__")) + self.assertIn("/ranges/front-range/", page) + with open(GOLDEN, encoding="utf-8") as f: + want = json.load(f)["/regions/us-co/"] + self.assertEqual(hashlib.sha256(normalise(page).encode()).hexdigest(), want) + + def test_a_state_with_no_place_has_no_block(self): + self.assertEqual(str(regions.place_links_for("US-UT", self.infos)), "") + _, _, body, _ = regions.region_page( + "us-ut", self.records, S, place_links=regions.place_links_for("US-UT", self.infos)) + self.assertNotIn("Parks, ranges and wilderness in Utah", str(body)) + + +class TrailLinkTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + small = [rec(301, "Small One", [("range", "wind-river-range"), ("park", "small")]), + rec(302, "Small Two", [("park", "small")])] + cls.records = wind_records(3) + small + cls.infos = infos(cls.records) + cls.rec = small[0] + + def test_a_trail_page_links_to_each_of_its_places_that_has_a_page_and_not_to_a_place_below_three(self): + links = str(trail.place_links(self.rec, self.infos)) + self.assertIn('Wind River Range', links) + self.assertNotIn("small", links) + body = str(trail.render(self.rec, S, self.records, place_infos=self.infos)[2]) + glance = body[body.index('class="glance'):body.index("All the facts")] + self.assertIn('Wind River Range', glance) + self.assertNotIn("/parks/small/", body) + self.assertIn("More in the Wind River Range", body) # the ways onward + + def test_a_trail_with_no_place_page_is_unchanged(self): + plain = str(trail.render(self.rec, S, self.records)[2]) + self.assertNotIn("/ranges/wind-river-range/", plain) + + +class LosingATrailTest(unittest.TestCase): + def test_losing_a_trail_removes_the_page_and_every_link(self): + three = wind_records(3) + got = infos(three) + self.assertIn(("range", "wind-river-range"), got) + two = three[:2] + gone = infos(two) + self.assertEqual(gone, {}) + _, _, hub = regions.regions_index_page(two, S, infos=gone) + self.assertNotIn("/ranges/wind-river-range/", str(hub)) + self.assertEqual(str(regions.place_links_for("US-WY", gone)), "") + self.assertEqual(str(trail.place_links(two[0], gone)), "") + + +class SearchTextTest(unittest.TestCase): + def tearDown(self): + searchtext.use_place_names({}) + + def test_search_text_holds_the_place_names(self): + # names with none of the place's words: a word already in the name tier + # is not repeated in the places tier (searchtext.tiers) + records = [rec(401, "Alpha Trail", [("range", "wind-river-range")]), + rec(402, "Bravo Trail", [("range", "wind-river-range")]), + rec(403, "Charlie Trail", [("range", "wind-river-range")])] + got = infos(records) + attr = searchtext.attribute(records[0], got) + self.assertIn("wind river range", attr) + # through a row, once the build has named each trail's places + searchtext.use_place_names({records[0]["id"]: ["Wind River Range"]}) + row = home.entry(records[0]) + self.assertIn("wind river range", row) + names = searchtext.place_names(records[0], got) + self.assertIn("Wind River Range", names) + + def test_search_text_without_places_is_as_before(self): + r = rec(9, "Plain Trail", []) + self.assertNotIn("wind river", searchtext.attribute(r)) + + +class SourcesTest(unittest.TestCase): + def test_sources_names_the_four_outline_publishers(self): + with open(os.path.join(ROOT, "SOURCES.md"), encoding="utf-8") as f: + text = f.read() + for want in ("National Park Service", "Wilderness Connect", "CPCAD", + "GMBA Mountain Inventory", "Open Government Licence", "CC BY 4.0", + "public domain"): + self.assertTrue(want in text, want) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/tests/test_place_page.py b/web/tests/test_place_page.py new file mode 100644 index 0000000..e69d415 --- /dev/null +++ b/web/tests/test_place_page.py @@ -0,0 +1,244 @@ +"""Park, range and wilderness pages (olt/placepages.py, through regions.place_page), +and their place in the built site: sitemap, structured data, navigation. + +Fixtures only: small records with [[place]] entries and a small places.toml in a +temporary directory, never sample data in the real records.""" +import html +import json +import os +import re +import sys +import tempfile +import unittest + +WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, WEB) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from olt import layout, pages, placepages, places, regions, seo, site # noqa: E402 +from test_facets import BANNED, site_words # noqa: E402 +from test_hike import fake # noqa: E402 + +S = site.Site("Long Hikes", "T", base_url="https://example.org", repo_url="https://github.com/o/r") +BOX = [-110.0, 42.5, -108.5, 43.5] + +REGISTRY = [ + {"kind": "range", "slug": "wind-river-range", "name": "Wind River Range", "where": ["WY"], + "source": "gmba-v2", "source_id": "1", "source_version": "2026-11-20", "box": BOX}, + {"kind": "park", "slug": "yosemite", "name": "Yosemite National Park", "where": ["CA"], + "source": "nps", "source_id": "YOSE", "source_version": "2026-11-20", + "box": [-119.9, 37.5, -119.2, 38.2]}, + {"kind": "park", "slug": "small", "name": "Small Park", "where": ["WY"], + "source": "nps", "source_id": "SMAL", "source_version": "2026-11-20", "box": BOX}, +] + + +def write_registry(root, entries=REGISTRY): + lines = [] + for e in entries: + box = ", ".join(str(v) for v in e["box"]) + where = ", ".join(f'"{c}"' for c in e["where"]) + within = f'\nwithin = [{", ".join(chr(34) + s + chr(34) for s in e["within"])}]' if e.get("within") else "" + lines.append(f'[[place]]\nslug = "{e["slug"]}"\nkind = "{e["kind"]}"\nname = "{e["name"]}"\n' + f'where = [{where}]{within}\nsource = "{e["source"]}"\nsource_id = "{e["source_id"]}"\n' + f'source_version = "{e["source_version"]}"\nbox = [{box}]\n') + with open(os.path.join(root, "places.toml"), "w", encoding="utf-8") as f: + f.write("\n".join(lines)) + + +def rec(i, name, pls, *, km=120, regs=("WY",), country="US", line=True, inside_km=123.456, date=""): + r = fake(i, km=km, regions=list(regs), country=country, line=line, + hike={"shape": "point-to-point", "terrain": ["alpine"], + "summary": f"A walk called {name}.", "days": [7, 14]}) + r["name"] = name + r["place"] = [{"kind": k, "slug": s, "basis": "track", "km": inside_km} for k, s in pls] + r["derived"]["bbox"] = [-109.5, 42.8, -109.0, 43.2] + if line: + r["derived"]["files"] = dict(r["derived"].get("files", {}), line="x.gpx") + if date: + r["history"] = [{"date": date}] + return r + + +def wind_records(n=10): + """n trails in the Wind River Range, names out of order, half over the state line.""" + out = [] + for i in range(n, 0, -1): + out.append(rec(100 + i, f"Wind Trail {chr(64 + i)}", [("range", "wind-river-range")], + km=90 + i * 10, regs=("WY",) if i % 2 else ("CO",), + date="2026-11-18" if i == 3 else "")) + return out + + +def yosemite_records(n=5): + return [rec(200 + i, f"Yosemite Trail {chr(64 + i)}", [("park", "yosemite")], + km=80 + i * 15, regs=("CA",)) for i in range(n, 0, -1)] + + +def build(records): + with tempfile.TemporaryDirectory() as d: + write_registry(d) + return {b.path: b for b in placepages.build(records, S, d)} + + +def text(fragment): + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", str(fragment)))) + + +class PlacePageTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.records = wind_records() + yosemite_records() + cls.built = build(cls.records) + + def test_a_place_with_three_trails_gets_a_page_and_one_with_two_does_not(self): + two = [rec(1, "One", [("park", "small")]), rec(2, "Two", [("park", "small")])] + self.assertEqual(build(two), {}) + three = two + [rec(3, "Three", [("park", "small")])] + self.assertIn("/parks/small/", build(three)) + self.assertIn("/parks/yosemite/", self.built) + self.assertIn("/ranges/wind-river-range/", self.built) + + def test_the_page_has_the_filter_bar_rows_and_map_before_the_summary(self): + body = str(self.built["/ranges/wind-river-range/"].body) + # browse_view wraps the listing (filter bar, then rows) in browse__list + # beside browse__map, as on a state page; the summary follows both. + self.assertLess(body.index('class="finder__bar"'), body.index('
  • Wind River Range", body) + self.assertIn('

    Mountain range · Wyoming

    ', body) + park = str(self.built["/parks/yosemite/"].body) + self.assertIn("

    Yosemite National Park

    ", park) + self.assertIn("5 trails in Yosemite National Park", text(park)) + + def test_the_breadcrumb_is_trails_places_name(self): + body = str(self.built["/ranges/wind-river-range/"].body) + crumbs = body[body.index('class="breadcrumb"'):body.index("")] + self.assertEqual(re.findall(r">([^<]+)", crumbs), ["Trails", "Places"]) + self.assertIn('
  • Wind River Range
  • ', crumbs) + self.assertEqual(seo.visible_breadcrumbs(body), + [("Trails", "/"), ("Places", "/regions/"), ("Wind River Range", "")]) + + def test_the_structured_data_is_a_collection_of_the_trails(self): + b = self.built["/parks/yosemite/"] + nodes = seo.collection_jsonld(b.path, S, title=b.title, description=b.description, recs=b.recs) + page = nodes[0] + self.assertEqual(page["@type"], "CollectionPage") + listing = page["mainEntity"] + self.assertEqual(listing["@type"], "ItemList") + self.assertEqual(listing["numberOfItems"], 5) + self.assertEqual([i["url"] for i in listing["itemListElement"]], + [f"https://example.org/trails/{r['id']}/" for r in b.recs]) + + +class BuiltPlacePagesTest(unittest.TestCase): + """One synthetic render_site: the pages written, in the sitemap, Places current.""" + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + repo, out = os.path.join(cls.tmp.name, "repo"), os.path.join(cls.tmp.name, "out") + cls.out = out + cls.records = wind_records() + yosemite_records() + for r in cls.records: + os.makedirs(os.path.join(repo, r["id"])) + with open(os.path.join(repo, r["id"], "trail.toml"), "w", encoding="utf-8") as f: + f.write(f'id = "{r["id"]}"\n') + write_registry(repo) + pages.render_site(cls.records, out, repo, site=S) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def read(self, *parts): + with open(os.path.join(self.out, *parts), encoding="utf-8") as f: + return f.read() + + def test_the_pages_are_written(self): + self.assertIn("Wind River Range", self.read("ranges", "wind-river-range", "index.html")) + self.assertIn("Yosemite National Park", self.read("parks", "yosemite", "index.html")) + self.assertFalse(os.path.exists(os.path.join(self.out, "parks", "small"))) + + def test_the_page_is_in_the_sitemap_with_the_newest_trail_date(self): + xml = self.read("sitemap.xml") + for p in ("/ranges/wind-river-range/", "/parks/yosemite/"): + self.assertIn(f"https://example.org{p}", xml, p) + row = next(ln for ln in xml.splitlines() if "/ranges/wind-river-range/" in ln) + self.assertIn("2026-11-18", row) # the newest of its trails + self.assertNotIn("/parks/small/", xml) + + def test_places_is_the_current_nav_item_on_a_place_page(self): + doc = self.read("parks", "yosemite", "index.html") + nav = re.search(r'', doc, re.S).group(1) + self.assertIn('Places', nav) + + def test_the_built_page_carries_the_collection_structured_data(self): + doc = self.read("ranges", "wind-river-range", "index.html") + m = re.search(r'', doc, re.S) + data = json.loads(m.group(1)) + nodes = data.get("@graph", [data]) + coll = next(n for n in nodes if n.get("@type") == "CollectionPage") + self.assertEqual(coll["mainEntity"]["numberOfItems"], 10) + crumbs = next(n for n in nodes if n.get("@type") == "BreadcrumbList") + self.assertEqual([i["name"] for i in crumbs["itemListElement"]], + ["Trails", "Places", "Wind River Range"]) + + def test_the_hub_state_and_trail_pages_of_the_same_build_link_here(self): + hub = self.read("regions", "index.html") + self.assertIn('Wind River Range', hub) + wyoming = self.read("regions", "us-wy", "index.html") + self.assertIn('aria-label="Parks, ranges and wilderness in Wyoming"', wyoming) + trail_page = self.read("trails", "t101", "index.html") + self.assertIn('Wind River Range', trail_page) + home_page = self.read("index.html") + self.assertIn("river range", home_page) # the rows' search words + + def test_the_state_pages_of_the_same_build_are_unchanged_in_shape(self): + # the golden test pins the exact bytes; here the same render still has them + doc = self.read("regions", "us-wy", "index.html") + self.assertIn("

    Wyoming

    ", doc) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/tests/test_places.py b/web/tests/test_places.py new file mode 100644 index 0000000..08b6554 --- /dev/null +++ b/web/tests/test_places.py @@ -0,0 +1,183 @@ +"""The place loader: registry, membership closed over `within`, and which places +get a page (olt/places.py). Fixtures only; no built site.""" +import os +import sys +import tempfile +import unittest + +WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, WEB) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from olt import places # noqa: E402 +from test_hike import fake # noqa: E402 + + +def entry(kind, slug, name, where=("WY",), within=()): + return {"kind": kind, "slug": slug, "name": name, "where": list(where), + "within": list(within), "source": "gmba-v2", "source_id": "1", + "source_version": "2026-11-20", "box": [-110.0, 42.5, -108.5, 43.5]} + + +def registry(*entries): + return {(e["kind"], e["slug"]): e for e in entries} + + +def rec(i, *pls, name=None): + r = fake(i) + if name: + r["name"] = name + r["place"] = [{"kind": k, "slug": s, "basis": b, + **({"km": 10.0} if b == "track" else {"source": "https://example.org/"})} + for k, s, b in pls] + return r + + +WIND = entry("range", "wind-river-range", "Wind River Range") +YOSE = entry("park", "yosemite", "Yosemite National Park", where=("CA",)) + + +class CollectTest(unittest.TestCase): + def test_a_range_gets_a_page_at_three_trails_and_not_at_two(self): + reg = registry(WIND) + two = [rec(1, ("range", "wind-river-range", "track")), + rec(2, ("range", "wind-river-range", "track"))] + self.assertEqual(places.collect(two, reg), {}) + three = two + [rec(3, ("range", "wind-river-range", "track"))] + got = places.collect(three, reg) + self.assertEqual(list(got), [("range", "wind-river-range")]) + info = got[("range", "wind-river-range")] + self.assertEqual(info["path"], "/ranges/wind-river-range/") + self.assertEqual(info["key"], "range/wind-river-range") + self.assertEqual([r["id"] for r in info["records"]], ["t1", "t2", "t3"]) + + def test_stated_and_track_trails_both_count(self): + reg = registry(WIND) + recs = [rec(1, ("range", "wind-river-range", "track")), + rec(2, ("range", "wind-river-range", "stated")), + rec(3, ("range", "wind-river-range", "track"))] + self.assertIn(("range", "wind-river-range"), places.collect(recs, reg)) + + def test_a_trail_in_a_nested_range_is_on_every_parent(self): + teton = entry("range", "teton-range", "Teton Range", within=("rocky-mountains",)) + rocky = entry("range", "rocky-mountains", "Rocky Mountains", + where=("WY", "CO", "MT"), within=("cordillera",)) + cord = entry("range", "cordillera", "Cordillera", where=("WY", "CO")) + reg = registry(teton, rocky, cord) + recs = [rec(i, ("range", "teton-range", "track")) for i in (1, 2, 3)] + mem = places.membership(recs, reg) + for slug in ("teton-range", "rocky-mountains", "cordillera"): + self.assertEqual([r["id"] for r in mem[("range", slug)]], ["t1", "t2", "t3"], slug) + self.assertIn(("range", "rocky-mountains"), places.collect(recs, reg)) + + def test_slugs_repeat_across_kinds(self): + park = entry("park", "glacier", "Glacier National Park", where=("MT",)) + wild = entry("wilderness", "glacier", "Glacier Peak Wilderness", where=("WA",)) + reg = registry(park, wild) + recs = [rec(i, ("park", "glacier", "track")) for i in (1, 2, 3)] + recs += [rec(i, ("wilderness", "glacier", "track")) for i in (4, 5, 6)] + got = places.collect(recs, reg) + self.assertEqual(got[("park", "glacier")]["path"], "/parks/glacier/") + self.assertEqual(got[("wilderness", "glacier")]["path"], "/wilderness/glacier/") + self.assertEqual([r["id"] for r in got[("park", "glacier")]["records"]], ["t1", "t2", "t3"]) + self.assertEqual([r["id"] for r in got[("wilderness", "glacier")]["records"]], ["t4", "t5", "t6"]) + + def test_a_parent_is_counted_once_when_a_trail_is_in_two_children(self): + a = entry("range", "a-range", "A Range", within=("parent-range",)) + b = entry("range", "b-range", "B Range", within=("parent-range",)) + p = entry("range", "parent-range", "Parent Range") + reg = registry(a, b, p) + recs = [rec(1, ("range", "a-range", "track"), ("range", "b-range", "track"))] + mem = places.membership(recs, reg) + self.assertEqual([r["id"] for r in mem[("range", "parent-range")]], ["t1"]) + + def test_a_doubled_wilderness_gets_no_page_when_the_park_holds_the_same_trails(self): + park = entry("park", "example", "Example National Park", where=("CA",)) + wild = entry("wilderness", "example", "Example National Park Wilderness", where=("CA",)) + reg = registry(park, wild) + recs = [rec(i, ("park", "example", "track"), ("wilderness", "example", "track")) + for i in (1, 2, 3)] + got = places.collect(recs, reg) + self.assertIn(("park", "example"), got) + self.assertNotIn(("wilderness", "example"), got) + # different sets: both keep their pages + recs.append(rec(4, ("wilderness", "example", "track"))) + self.assertIn(("wilderness", "example"), places.collect(recs, reg)) + + def test_records_are_a_to_z(self): + reg = registry(WIND) + recs = [rec(1, ("range", "wind-river-range", "track"), name="Zebra Trail"), + rec(2, ("range", "wind-river-range", "track"), name="The Apple Trail"), + rec(3, ("range", "wind-river-range", "track"), name="Middle Trail")] + got = places.collect(recs, reg)[("range", "wind-river-range")] + self.assertEqual([r["name"] for r in got["records"]], + ["The Apple Trail", "Middle Trail", "Zebra Trail"]) + + def test_title_name_adds_the_state_for_a_range_with_one_state_only(self): + reg = registry(WIND, YOSE) + recs = [rec(i, ("range", "wind-river-range", "track"), ("park", "yosemite", "track")) + for i in (1, 2, 3)] + got = places.collect(recs, reg) + self.assertEqual(got[("range", "wind-river-range")]["title_name"], + "Wind River Range, Wyoming") + self.assertEqual(places.title_name(got[("range", "wind-river-range")]), + "Wind River Range, Wyoming") + self.assertEqual(got[("park", "yosemite")]["title_name"], "Yosemite National Park") + multi = dict(got[("range", "wind-river-range")], where=["WY", "CO", "MT", "UT"]) + self.assertEqual(places.title_name(multi), "Wind River Range") + + def test_of_record_leaves_out_a_place_below_the_minimum(self): + small = entry("park", "small", "Small Park", where=("WY",)) + reg = registry(WIND, small) + recs = [rec(1, ("range", "wind-river-range", "track"), ("park", "small", "track"))] + recs += [rec(i, ("range", "wind-river-range", "track")) for i in (2, 3)] + infos = places.collect(recs, reg) + mine = places.of_record(recs[0], infos) + self.assertEqual([(i["kind"], i["slug"]) for i in mine], [("range", "wind-river-range")]) + + def test_of_record_includes_a_parent_range(self): + teton = entry("range", "teton-range", "Teton Range", within=("rocky-mountains",)) + rocky = entry("range", "rocky-mountains", "Rocky Mountains", where=("WY", "CO")) + reg = registry(teton, rocky) + recs = [rec(i, ("range", "teton-range", "track")) for i in (1, 2, 3)] + infos = places.collect(recs, reg) + names = [i["name"] for i in places.of_record(recs[0], infos)] + self.assertEqual(names, ["Rocky Mountains", "Teton Range"]) + + def test_in_state_matches_the_registry_where(self): + reg = registry(WIND, YOSE) + recs = [rec(i, ("range", "wind-river-range", "track"), ("park", "yosemite", "track")) + for i in (1, 2, 3)] + infos = places.collect(recs, reg) + wy = places.in_state(infos, "US-WY") + self.assertEqual([i["name"] for i in wy], ["Wind River Range"]) + self.assertEqual(places.in_state(infos, "US-UT"), []) + + def test_path_and_kinds(self): + self.assertEqual(places.path("park", "glacier"), "/parks/glacier/") + self.assertEqual(places.path("range", "wind-river-range"), "/ranges/wind-river-range/") + self.assertEqual(places.path("wilderness", "bob-marshall"), "/wilderness/bob-marshall/") + self.assertEqual(places.KINDS["park"].segment, "parks") + self.assertEqual(places.KINDS["range"].segment, "ranges") + self.assertEqual(places.KINDS["wilderness"].segment, "wilderness") + self.assertEqual(places.PAGE_MIN, 3) + + def test_load_reads_places_toml_keyed_by_kind_and_slug(self): + with tempfile.TemporaryDirectory() as d: + with open(os.path.join(d, "places.toml"), "w", encoding="utf-8") as f: + f.write('[[place]]\nslug = "wind-river-range"\nkind = "range"\n' + 'name = "Wind River Range"\nwhere = ["WY"]\nsource = "gmba-v2"\n' + 'source_id = "1"\nsource_version = "2026-11-20"\n' + 'box = [-110.0, 42.5, -108.5, 43.5]\n') + reg = places.load(d) + self.assertEqual(reg[("range", "wind-river-range")]["name"], "Wind River Range") + + def test_an_unknown_place_on_a_record_is_ignored(self): + reg = registry(WIND) + recs = [rec(1, ("range", "nowhere", "track"))] + self.assertEqual(places.collect(recs, reg), {}) + self.assertEqual(places.membership(recs, reg)[("range", "wind-river-range")], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/tests/test_state_pages_unchanged.py b/web/tests/test_state_pages_unchanged.py index e76d354..d2224d7 100644 --- a/web/tests/test_state_pages_unchanged.py +++ b/web/tests/test_state_pages_unchanged.py @@ -16,7 +16,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, WEB) sys.path.insert(0, HERE) -from olt import bounds, facets, placefacets, regions, site # noqa: E402 +from olt import bounds, facets, home, placefacets, regions, searchtext, site # noqa: E402 from test_hike import fake # noqa: E402 GOLDEN = os.path.join(HERE, "golden", "state-pages.json") @@ -95,6 +95,32 @@ def build_map(): return out +class AllowedDifferencesTest(unittest.TestCase): + def test_state_pages_differ_only_in_data_search_and_the_new_block(self): + # data-search gains the place names, and nothing else about a row changes + rec = fixtures()[0] + plain = home.entry(rec) + searchtext.use_place_names({rec["id"]: ["Wind River Range"]}) + try: + with_place = home.entry(rec) + finally: + searchtext.use_place_names({}) + self.assertIn("wind river range", with_place) + self.assertNotEqual(plain, with_place) + self.assertEqual(normalise(plain), normalise(with_place)) + # the place-links nav is the other allowed addition to a state page + records = fixtures() + s = site.Site("Long Hikes", "T", repo_url="https://github.com/o/r") + block = ('') + plain_page = regions.region_page("us-co", records, s) + linked_page = regions.region_page("us-co", records, s, place_links=block) + self.assertNotEqual(str(plain_page[2]), str(linked_page[2])) + self.assertEqual(normalise(str(plain_page[2])), normalise(str(linked_page[2]))) + self.assertEqual(plain_page[0], linked_page[0]) + self.assertEqual(plain_page[1], linked_page[1]) + + class StatePagesUnchangedTest(unittest.TestCase): def test_every_state_group_and_state_list_page_is_byte_identical_after_normalising(self): with open(GOLDEN, encoding="utf-8") as f: