"""Places (/regions/, /regions//), lists (/lists/, /lists//) and the Routes list (/routes/). 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 . import browse, common, facets, home, words from .markup import Markup, esc def collect_regions(records): """slug -> {key, code, country, name, group, records} for every state and province a trail names; plus the trails that name all of Canada, separately.""" by_slug = {} across = [] for r in records: for key in facets.place_keys(r): if key == facets.ACROSS_CANADA: across.append(r) continue slug = key.lower() country, code = key.split("-", 1) info = by_slug.setdefault(slug, {"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"]): info["records"].append(r) for info in by_slug.values(): info["records"].sort(key=home.sort_name) across.sort(key=home.sort_name) return by_slug, across def group_records(records, group): return [r for r in records if group in facets.place_groups(r)] def _gpx_count(recs): return sum(1 for r in recs if facets.gpx_here(r)) def _plural(n, word="trail"): return f"{n} {word}{'' if n == 1 else 's'}" def regions_index_page(records, site): """(title, description, body) for /regions/: the Places hub.""" by_slug, across = collect_regions(records) blocks = "" jump = [] for g, name, keys in facets.PLACE_GROUPS: infos = sorted((by_slug[k.lower()] for k in keys if k.lower() in by_slug), key=lambda i: i["name"]) if not infos: continue recs = group_records(records, g) jump.append(f'
  • {esc(name)} {len(recs)}
  • ') rows = "".join( f'
  • {esc(i["name"])}' f'{_plural(len(i["records"]))}
  • ' for i in infos) blocks += f"""

    {esc(name)}

    {_plural(len(recs))}, {_gpx_count(recs)} with a GPX here. See them with the filters

      {rows}
    """ if across: links = ", ".join(f'{common.name(r)}' for r in across) jump.append(f'
  • {facets.ACROSS_CANADA_NAME} {len(across)}
  • ') blocks += f"""

    {facets.ACROSS_CANADA_NAME}

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

    """ n_us = sum(1 for r in records if "US" in common.countries(r)) n_ca = sum(1 for r in records if "CA" in common.countries(r)) 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.

      {"".join(jump)}
    {blocks}
    """ return "Places", "Long trails by state and province, grouped into parts of the United States and Canada.", Markup(body) def region_page(slug, records, site): """(title, description, body, needs_map) for /regions//: the trails in one state or province.""" 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) 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 "" 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. Narrow them with the filters.

    {home.overview_map(recs, f"Map of the trails in {info['name']}")} {home.results(recs)} {nav}
    """ title = info["name"] desc = f"{_plural(len(recs))} in {info['name']}, {country}: length, time and where to get the GPX." return title, desc, Markup(body), home.has_overview_map(recs) def route_guides(rec): """A route's guides, compact, placed last in its row on /routes/.""" items = "" for g in rec.get("guide", []): access = g.get("access", "") price = f' · {esc(g["price"])}' if g.get("price") else "" 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'
      {items}
    ') def routes_page(records, site, repo_root=None): """(title, description, body, needs_map) for /routes/: the Routes list.""" routes = [r for r in records if facets.kind(r) == "route"] by_author = collections.defaultdict(list) for r in routes: by_author[facets.author(r) or "Author not named"].append(r) groups = [(f"By {esc(a)}", sorted(by_author[a], key=home.sort_name), route_guides) for a in sorted(by_author, key=str.lower)] n_gpx = _gpx_count(routes) body = f"""

    A list

    Routes

    {esc(facets.ROUTE_DEFINITION)}

    Every other trail on this site is an official trail. Being a route says who looks after it, not how rough it is: some routes are on maintained trail all the way, and some official trails have long road walks. The Walking line on each trail’s page says what the walking is.

    {_plural(len(routes), "route")}, by {len(by_author)} authors. {n_gpx} {"has" if n_gpx == 1 else "have"} a GPX here; for the rest, each route’s page says whether its author gives the track away, sells it, or does not publish it. Narrow them with the filters.

    {home.overview_map(routes, "Map of the routes with a GPX here")} {home.results(groups=groups, routes_list=True)}
    """ return "Routes", f"{_plural(len(routes), 'route')} in the United States and Canada, by author, with their guides.", Markup(body), home.has_overview_map(routes) def list_page(lst, recs, total, site): """(title, description, body, needs_map) for /lists//.""" n_gpx = _gpx_count(recs) rule = (f"Lists are picked out by rule from each trail’s facts, so they change as trails are added " f"or corrected. A list is shown when it has at least {browse.MIN_SIZE} trails and no more than " f"{round(browse.MAX_SHARE * 100)}% of the {total}.") body = f"""

    A list

    {esc(lst.title)}

    {esc(lst.blurb)} {_plural(len(recs))}, {n_gpx} with a GPX here.

    {home.overview_map(recs, f"Map of the trails in the list {lst.title}")} {home.results(recs, default_sort=lst.sort)}

    {rule}

    """ return lst.title, f"{lst.title}: {lst.blurb}", Markup(body), home.has_overview_map(recs) def lists_index_page(records, site): """(title, description, body) for /lists/: every list shown today, with a few of its trails.""" cards = [] for lst, recs in browse.shown(records): sample = "".join( f'
  • {common.name(r)} ' f'{words.length(r["length_km"], "short", r["derived"]["length_mi"])}
  • ' for r in recs[:4]) cards.append(f"""
  • {esc(lst.title)} {len(recs)}

    {esc(lst.blurb)}

      {sample}

    See all {len(recs)}: {esc(lst.title)}

  • """) body = f"""

    Lists

    Ready-made selections of the {len(records)} trails, a way to start. Each is picked out by rule from what each trail’s page says, so a list grows as trails are added.

      {"".join(cards)}

    A list is shown when it has at least {browse.MIN_SIZE} trails and no more than {round(browse.MAX_SHARE * 100)}% of all of them. To combine conditions, use the filters on the home page.

    """ return "Lists", "Ready-made lists of long trails: National Scenic Trails, routes, loops, the longest and more.", Markup(body)