"""Region pages (/regions/, /regions//) and the routes page (/routes/). Both list records with home.results(), the same list the home page shows. """ import collections from . import common, docs, home, words from .markup import Markup, esc # The /regions/ anchor and the finder's region key for records that name all of Canada. CANADA_WIDE_ID = "canada-wide" CANADA_WIDE_KEY = words.region_key(words.ALL_CANADA, "CA") # "CA-*" def region_country(code): return words.region_country(code) if code != words.ALL_CANADA else "" def region_slug(code, fallback_country=""): return words.region_key(code, region_country(code) or fallback_country).lower() def region_path(code, fallback_country=""): return f"/regions/{region_slug(code, fallback_country)}/" def collect_regions(records): """slug -> {code, country, name, records}; plus Canada-wide records separately.""" by_slug = {} canada_wide = [] for r in records: for code in r.get("regions", []): if code == words.ALL_CANADA: canada_wide.append(r) continue country = region_country(code) or r["country"] slug = region_slug(code, r["country"]) info = by_slug.setdefault(slug, {"code": code, "country": country, "name": words.region_name(code), "records": []}) if all(x["id"] != r["id"] for x in info["records"]): info["records"].append(r) for info in by_slug.values(): info["records"].sort(key=home.sort_name) canada_wide.sort(key=home.sort_name) return by_slug, canada_wide def country_records(records, country): """Every record that touches a country: listed on one of its region pages, or Canada-wide.""" return [r for r in records if country in common.countries(r)] def _bbox_attr(recs): boxes = [r["derived"]["bbox"] for r in recs if r["derived"].get("bbox")] if not boxes: return "" box = [min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)] return f' data-bbox="{",".join(f"{v:.4f}" for v in box)}"' def _region_map(recs, title): ids = [r["id"] for r in recs if "line" in r["derived"]["files"]] if not ids: return ('

No downloadable line in this region yet, so there is ' 'nothing to draw. The records below say why.

') return f"""

The map needs JavaScript. The list below has every record.

  • {common.SWATCH_LINE}Designated trail
  • {common.SWATCH_ROUTE}Person-defined route

{len(ids)} line{"s" if len(ids) != 1 else ""} in this region, simplified for display. Select a line for its name.

""" def regions_index_page(records, site): by_slug, canada_wide = collect_regions(records) blocks = "" tally = '
Records
' + str(len(records)) + '
' for country in ("US", "CA"): n_country = len(country_records(records, country)) tally += (f'
{esc(words.COUNTRIES[country])}
' f'
{n_country}
') infos = sorted((i for i in by_slug.values() if i["country"] == country), key=lambda i: i["name"].lower()) rows = "" for info in infos: lines = sum(1 for r in info["records"] if common.has_line(r)) rows += (f'{esc(info["name"])} ' f'{esc(info["code"])}' f'{len(info["records"])}{lines}') extra = "" if country == "CA" and canada_wide: links = ", ".join(f'{common.name(r)}' for r in canada_wide) extra = (f'

All provinces and territories

' f'

These records name all provinces and territories rather than ' f'one province, so they have no single region page and are not counted under each ' f'province: {links}. Open in the trail finder.

') unit = "state" if country == "US" else "province or territory, or all of them" blocks += f"""

{esc(words.COUNTRIES[country])}

{n_country} records name at least one {unit}. Each is counted once, whichever country it is filed under.

{rows}
State, province or territoryRecordsWith a downloadable line
{extra}
""" body = f"""

Browse

Regions

Every state, province and territory a record names. A record that crosses several regions appears on each region's page, under the country that region belongs to.

{tally}
{blocks}
""" return "Regions", "Long trails by state, province and territory, with counts of records and lines.", Markup(body) def region_page(slug, records, site): by_slug, _ = collect_regions(records) info = by_slug[slug] recs = info["records"] lines = sum(1 for r in recs if common.has_line(r)) key = words.region_key(info["code"], info["country"]) same = sorted((s for s, i in by_slug.items() if i["country"] == info["country"]), key=lambda s: by_slug[s]["name"].lower()) idx = same.index(slug) neighbours = [] if idx > 0: p = by_slug[same[idx - 1]] neighbours.append(f'← {esc(p["name"])}') if idx + 1 < len(same): n = by_slug[same[idx + 1]] neighbours.append(f'{esc(n["name"])} →') nav = " · ".join(neighbours) with_line = (f'With a line' if lines else "With a line") body = f"""

{esc(words.COUNTRIES[info["country"]])} · {esc(info["code"])}

{esc(info["name"])}

{len(recs)} record{"s" if len(recs) != 1 else ""}, {lines} with a downloadable line.

Records
{len(recs)}
{common.SWATCH_LINE}{with_line}
{lines}
{common.SWATCH_NONE}Records only
{len(recs) - lines}

Lines in {esc(info["name"])}

Only lines in this region are drawn.

{_region_map(recs, info["name"])}

Trails and routes in {esc(info["name"])}

Open these in the trail finder to search and filter them.

{home.results(recs)}
""" title = info["name"] return title, f"{len(recs)} long trails and routes in {info['name']}, {words.COUNTRIES[info['country']]}.", Markup(body), bool(lines) def route_guides(rec): """A route's guides, placed last in its list row on /routes/.""" items = "" for g in rec.get("guide", []): access = g.get("access", "") price = "" if g.get("price"): price = f' · {esc(g["price"])}' if g.get("price_checked"): price += f' (read {esc(g["price_checked"])})' fmt = f' · {esc(g["format"])}' if g.get("format") else "" items += (f'
  • {esc(g.get("title", ""))}' f' {esc(words.ACCESS.get(access, access))}' f'{fmt}{price}
  • ') if not items: return "" return (f'\n

    Guides

    ' f'
    ') def routes_page(records, site, repo_root): """(title, description, body) for /routes/.""" readme = docs.sections_map(docs.read_doc(repo_root, "README.md")) inc = readme.get("Inclusion rule", "") paras = [p for p in inc.split("\n\n") if "Person-defined rout" in p and "at the same 50-mile floor" in p] bullets = [p for p in inc.split("\n\n") if "The creator sells" in p] explainer = "\n\n".join(paras + bullets) or readme.get("Person-defined routes", "") intro = docs.render_doc("## What a person-defined route is\n\n" + explainer, site) policy_items = "" for key in ("open", "sold", "withheld", "unclear"): lab, short, rule = words.POLICIES[key] policy_items += f'
  • {common.policy_chip(key)}{esc(short)}. {esc(rule)}
  • ' policies = Markup(f'
      {policy_items}
    ') routes = [r for r in records if common.is_route(r)] by_creator = collections.defaultdict(list) for r in routes: by_creator[r.get("route", {}).get("creator", "") or "Unknown"].append(r) groups = [(esc(creator), sorted(by_creator[creator], key=home.sort_name), route_guides) for creator in sorted(by_creator, key=str.lower)] body = f"""

    Person-defined routes

    Routes

    {len(routes)} routes worked out and published by a person or a small group.

    {intro}

    The four line policies

    {policies}

    See the routes in the trail finder, or read a route below.

    Routes by creator

    Each route links to its record; its guides link out to the creator's or publisher's page.

    {home.results(groups=groups)}
    """ return "Routes", f"{len(routes)} person-defined routes by creator, with line policies and guides.", Markup(body)