"""The home page: what the site is, the overview map, and the trail finder with every record. The list of records (results(), entry()) is shared with the region pages and the routes page, so every list of records on the site looks and reads the same. """ import collections import math import re from . import common, words from .markup import Markup, esc # Length range choices (km) for the filters. length_steps() adds a top step # above the longest record, so a chosen upper bound can always reach every record. LENGTH_STEPS = (60, 80, 100, 150, 200, 300, 500, 1000, 2000, 4000, 8000) def length_steps(records): """LENGTH_STEPS plus a round step at or above the longest record, when that is longer.""" longest = max((r["length_km"] for r in records), default=0) steps = list(LENGTH_STEPS) if longest > steps[-1]: magnitude = 10 ** int(math.floor(math.log10(longest))) steps.append(int(math.ceil(longest / magnitude) * magnitude)) return steps def counts(records): """Counts for the filters. A record counts under each country it touches (its own country and its regions' countries) and under each of its regions, as on /regions/; a Canada-wide record counts under "region:CA-*", not under each province.""" c = collections.Counter() for r in records: c["total"] += 1 c[common.kind(r)] += 1 c["line" if common.has_line(r) else "record_only"] += 1 if common.is_route(r): c["route_line" if common.has_line(r) else "route_record_only"] += 1 c["policy:" + common.policy(r)] += 1 c["tier:" + r.get("tier", "")] += 1 for country in common.countries(r): c["country:" + country] += 1 for key in set(words.region_key(code, r["country"]) for code in r.get("regions", [])): c["region:" + key] += 1 return c def overview_bbox(records): """data-bbox attribute: the extent of every line, so the map opens on it before the data loads.""" boxes = [r["derived"]["bbox"] for r in records 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 sort_name(rec): return re.sub(r"^The ", "", rec["name"]).lower() def entry(rec, *, level=3, extra=""): """One record in a list. Its data-* attributes drive the filters in app.js. level: the heading level of the record's name. extra: HTML placed last in the row. """ route = common.is_route(rec) if route: r = rec["route"] desc = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "") elif rec.get("tier") == "national" and common.designated_year(rec): desc = "Designated " + common.designated_year(rec) else: desc = rec.get("designation", "") where = Markup(f'{common.regions_html(rec, linked=True)} ' f'{esc(words.COUNTRIES.get(rec["country"], rec["country"]))}') policy = common.policy_chip(common.policy(rec)) if route else "" partial = common.line_differs(rec) if common.has_line(rec): partial_note = (f'

{esc(common.partial_short_text(rec))}

' if partial else "") line = (f'{common.SWATCH_ROUTE if route else common.SWATCH_LINE}Track{policy}' f'{partial_note}' f'GeoJSON, GPX' f'{esc(common.short_source(rec))} · {esc(common.licence_label(rec))}') note = "" else: line = f'{common.SWATCH_NONE}Record only{policy}' note = (f'\n

Why there is no track: ' f'{esc(common.absent_reason_short(rec))}

') regions = " ".join(words.region_key(c, rec["country"]) for c in rec.get("regions", [])) search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"]] + ([rec["route"]["creator"]] if route else [])).lower() abbr_cls = "entry__abbr" if common.shield_url(rec) else "entry__abbr vh" data = (f' data-id="{esc(rec["id"])}" data-country="{esc(rec["country"])}"' f' data-countries="{esc(" ".join(common.countries(rec)))}" data-regions="{esc(regions)}"' f' data-km="{rec["length_km"]}" data-kind="{esc(common.kind(rec))}"' f' data-line="{"yes" if common.has_line(rec) else "no"}"{' data-partial="yes"' if partial else ""}' f' data-tier="{esc(rec.get("tier", ""))}"' f' data-policy="{esc(common.policy(rec))}" data-name="{esc(sort_name(rec))}" data-search="{esc(search)}"') h = f"h{level}" return f"""
  • {common.plate(rec)}

    {common.tags(rec, with_policy=False)}

    <{h} class="entry__name">{common.name(rec)} {esc(rec.get("short_name", ""))}

    {esc(desc)}

    {where}

    Length
    {words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}
    Track
    {line}
    {note}{extra}
  • """ def _length_options(steps, selected_any_last): opts = [f'' for km in steps] if selected_any_last: return "".join(opts[1:]) + '' return '' + "".join(opts[:-1]) def region_options(c): """The region filter: each state, province and territory a record names, with the count its /regions/ page shows; the Canada-wide records under their own option.""" groups = [] for country, table in (("US", words.US_STATES), ("CA", words.CA_PROVINCES)): opts = [] if country == "CA" and c["region:CA-*"]: key = words.region_key(words.ALL_CANADA, "CA") opts.append(f'') for code, name in sorted(table.items(), key=lambda kv: kv[1]): n = c[f"region:{country}-{code}"] if n: opts.append(f'') groups.append(f'{"".join(opts)}') return "".join(groups) def finder_form(c, steps=LENGTH_STEPS): tier_opts = "".join( f'' for t in ("national", "regional", "short", "deferred", "candidate") if c["tier:" + t]) policy_opts = "".join( f'' for p in ("open", "sold", "withheld", "unclear") if c["policy:" + p]) return f"""""" # The length strip's ticks (style.css .loglen): 100, 1,000 and 10,000 km. SCALE_KM = (100, 1000, 10000) def list_head(): """The column head over a list. The scale ticks follow the reader's unit preference with the same len__km / len__mi pair the lengths use.""" ticks = [] for i, km in enumerate(SCALE_KM): unit = " km" if i == len(SCALE_KM) - 1 else "" mi_unit = " mi" if i == len(SCALE_KM) - 1 else "" ticks.append(f'{km:,}{unit}' f'{words.fmt_int(words.km_to_mi(km))}{mi_unit}') return f"""""" UNITS_TOGGLE = """
    Lengths
    """ SORT_SELECT = """""" def key(): return f"""""" def results(recs=None, *, finder=False, groups=None): """The list of records, as every page shows it: div.results > head, key, list head, ol.entries. finder: the home page's list, driven by the finder form (live count, sort, empty state). groups: [(heading, records, extra_fn)] to list the records under level-3 headings (the routes page); extra_fn(rec) gives HTML placed last in each row. """ if groups is None: groups = [(None, recs, None)] total = sum(len(g[1]) for g in groups) noun = "record" if total == 1 else "records" lists = "" for heading, items, extra_fn in groups: level = 4 if heading else 3 rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "") for r in items) if heading: lists += f'\n

    {heading}

    ' list_id = ' id="entries"' if finder else "" lists += f'\n
      \n{rows}\n
    ' if finder: count = (f'

    ' f'{total} of {total} {noun}

    ') tools = SORT_SELECT + "\n " + UNITS_TOGGLE empty = """ """ else: count = f'

    {total} {noun}

    ' tools = UNITS_TOGGLE empty = "" return Markup(f"""
    {count}
    {tools}
    {key()} {list_head()}{lists}{empty}
    """) def render(records, site): """The home page body (HTML) for every record.""" c = counts(records) recs = sorted(records, key=sort_name) total = c["total"] lede = (f"A record for each of {total} long trails and routes, as a rule 50 miles (80 km) or more: " "what it is, how long it is, who publishes it, and on what terms its track may be passed on. " "Where the terms allow, download the track as GPX or GeoJSON.") contribute = "" if site.repo_url: contribute = (f'

    Something wrong, or a trail missing? ' f'Report a problem or ' f'suggest a trail; ' f'the records are text files anyone can fix or add to.

    ') return f"""

    A public dataset · United States and Canada

    {esc(site.tagline)}

    {lede}

    This is a dataset, not a navigation product. Tracks vary in quality, some trails are unfinished, and some records have no track at all; each of those says why.

    {contribute}

    Find a trail

    Records
    {total}
    Designated trails
    {c["designated"]}
    Person-defined routes
    {c["route"]}
    {common.SWATCH_LINE}With a track
    {c["line"]}
    {common.SWATCH_NONE}Records only
    {c["record_only"]}

    Every track in the dataset

    {c["line"]} tracks, simplified for display. Select a trail on the map for its name.

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

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

    Tracks are simplified to about 750 m here; each keeps the credit and licence named on its page. Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.

    Find a trail

    Search, then narrow by country, region, length, kind and track

    {finder_form(c, length_steps(records))} {results(recs, finder=True)}
    """