"""The home page: the catalogue. Search, the filters, and the trails as a list and on a map. The list (results(), entry()) is shared with the place pages and the lists, so every list of trails on the site looks and reads the same. The filters are the attributes in olt/facets.py, under the same names the trail pages use. """ import collections import math import re from . import browse, common, elevation, facets, hike, words from .markup import Markup, esc # Length range choices (km) for the filters. length_steps() adds a top step # above the longest trail, so a chosen upper bound can always reach every trail. 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 trail, 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 filter options: each Where value, Time band, month, terrain, Kind, Walking, Shape and GPX status, as the filter would find them.""" c = collections.Counter() for r in records: c["total"] += 1 for tok in facets.where_tokens(r): c["where:" + tok] += 1 c["time:" + facets.time_band(r)] += 1 for m in facets.months(r): c[f"month:{m}"] += 1 for t in facets.terrain(r): c["terrain:" + t] += 1 c["kind:" + facets.kind(r)] += 1 if facets.walking(r): c["walking:" + facets.walking(r)] += 1 if facets.shape(r): c["shape:" + facets.shape(r)] += 1 c["gpx:" + facets.gpx(r)] += 1 if facets.gpx_here(r): c["gpx_here"] += 1 return c def overview_bbox(records): """data-bbox attribute: the extent of every track, 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() # A row ------------------------------------------------------------------------ def entry_desc(rec): """The one-line description of a row: the [hike] summary's first sentence, else the trail's designation (an official trail) or nothing (a route says who made it).""" one = hike.one_line(rec) if one: return one if facets.kind(rec) == "route": return "" return rec.get("designation", "") def where_html(rec): """The states and provinces of a row, each linked to its place page, and the country.""" parts = [] for key in facets.place_keys(rec): name = facets.place_name(key) text = esc(name) if key == facets.ACROSS_CANADA else \ Markup(f'{esc(key.split("-", 1)[1])}') parts.append(f'{text}') country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec)) return Markup(" ".join(parts) + f' {esc(country)}') def gpx_cell(rec): status = facets.gpx(rec) route = facets.kind(rec) == "route" if facets.gpx_here(rec): swatch = common.SWATCH_ROUTE if route else common.SWATCH_LINE partial = (f'

{esc(common.partial_short_text(rec))}

' if common.line_differs(rec) else "") return (f'{swatch}{esc(facets.GPX_SHORT[status])}' f'GPX and GeoJSON{partial}') return f'{common.SWATCH_NONE}{esc(facets.GPX_SHORT[status])}' def entry(rec, *, level=3, extra="", routes_list=False): """One trail in a list. Its data-* attributes drive the filters in app.js. level: the heading level of the trail's name. extra: HTML placed last in the row. routes_list: the Routes list, whose "By " headings already say what the row's Route badge and "Route by" line would repeat; both are left out there. """ route = facets.kind(rec) == "route" lo, hi, est = facets.time_days(rec) search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"], facets.author(rec)]).lower() abbr_cls = "entry__abbr" if common.shield_url(rec) else "entry__abbr vh" elev = elevation.get(rec) # A climb worked out from a track that covers only part of the trail, or more # than the trail, would mislead in a list; the trail's own page gives it with # its caveat. if elev and elevation.coverage_kind(elev): elev = None data = { "id": rec["id"], "where": " ".join(facets.where_tokens(rec)), "km": rec["length_km"], "climb": elev["ascent_m"] if elev else "", "days": hi, "time": facets.time_band(rec), "months": " ".join(map(str, facets.months(rec))), "terrain": " ".join(facets.terrain(rec)), "kind": facets.kind(rec), "walking": facets.walking(rec), "shape": facets.shape(rec), "gpx": facets.gpx(rec), "name": sort_name(rec), "search": search.strip(), } attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items()) if common.line_differs(rec): attrs += ' data-partial="yes"' h = f"h{level}" tag_html = common.badges(rec, route_tag=not routes_list) kicker = f'\n

{tag_html}

' if tag_html else "" by = f'\n

{esc(facets.route_by(rec))}

' if route and not routes_list else "" desc = entry_desc(rec) desc_html = f'\n

{esc(desc)}

' if desc else "" time_html = esc(facets.time_text(rec)) + (' estimate' if est else "") climb_html = (f'\n
Climb
{words.elevation(elev["ascent_m"], "stack")}' f'computed
') if elev else "" return f"""
  • {common.plate(rec)}
    {kicker} <{h} class="entry__name">{common.name(rec)} {esc(rec.get("short_name", ""))}{by}{desc_html}

    {where_html(rec)}

    Length
    {words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}
    Time
    {time_html}
    GPX
    {gpx_cell(rec)}
    {climb_html}
    {extra}
  • """ # The filters ------------------------------------------------------------------ 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 where_options(c): """The Where filter: the two countries, then each place group with its states and provinces.""" opts = [f''] for code in ("US", "CA"): if c["where:" + code]: opts.append(f'') for g, name, keys in facets.PLACE_GROUPS: if not c["where:g:" + g]: continue inner = [f''] for key in sorted(keys, key=facets.place_name): if c["where:" + key]: inner.append(f'') opts.append(f'{"".join(inner)}') if c["where:" + facets.ACROSS_CANADA]: opts.append(f'') return "".join(opts) def _checks(name, items, c, prefix, hints=None): """Checkboxes for a multi-choice facet: (value, label) items with their counts.""" out = [] for value, label in items: n = c[f"{prefix}:{value}"] if not n: continue hint = f'{esc(hints[value])}' if hints and hints.get(value) else "" out.append(f'') return "".join(out) def _missing(records, key): """The note under an optional facet: how many trails it leaves out while it is in use.""" _, without = facets.coverage(records, key) if not without: return "" return (f'') def finder_form(records, c=None, steps=None): """Search and the first-rank filters in view; Walking, Shape and GPX behind "More".""" c = c or counts(records) steps = steps or length_steps(records) first, more = [], [] first.append(f"""
    """) first.append(f"""
    {facets.LENGTH}

    Any length.

    """) first.append(f"""
    {facets.TIME}
    {_checks("time", [(k, label) for k, label, _ in facets.TIME_BANDS], c, "time")}

    To walk it all. Where no source says, it is estimated from the length.

    """) if facets.offered(records, "season"): month_opts = "".join(f'' for i, m in enumerate(facets.MONTHS, 1)) first.append(f"""

    Trails usually walked in that month.

    {_missing(records, "season")}
    """) if facets.offered(records, "terrain"): first.append(f"""
    {facets.TERRAIN}
    {_checks("terrain", facets.TERRAIN_VALUES.items(), c, "terrain")}
    {_missing(records, "terrain")}
    """) first.append(f"""
    {facets.KIND}

    What is a route?

    """) if facets.offered(records, "walking"): more.append(f"""
    {facets.WALKING} {_checks("walking", facets.WALKING_VALUES.items(), c, "walking", facets.WALKING_HINT)} {_missing(records, "walking")}
    """) if facets.offered(records, "shape"): more.append(f"""
    {facets.SHAPE} {_checks("shape", facets.SHAPES.items(), c, "shape")} {_missing(records, "shape")}
    """) more.append(f"""
    {facets.GPX} {_checks("gpx", facets.GPX_STATUS.items(), c, "gpx")}
    """) return f"""""" # The list --------------------------------------------------------------------- # 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(official=True): """official: False on a list of routes only, which has no official trail to explain.""" first = f"
  • {common.SWATCH_LINE}Official trail with a GPX here
  • \n " if official else "" return f"""""" def results(recs=None, *, finder=False, groups=None, routes_list=False): """The list of trails, as every page shows it: div.results > head, key, list head, ol.entries. finder: the home page's list, driven by the filters (live count, sort, empty state). groups: [(heading, trails, extra_fn)] to list the trails under level-3 headings; extra_fn(rec) gives HTML placed last in each row. routes_list: passed to entry() for the Routes list (see there). """ if groups is None: groups = [(None, recs, None)] total = sum(len(g[1]) for g in groups) shown = [r for g in groups for r in g[1]] only_routes = bool(shown) and all(facets.kind(r) == "route" for r in shown) noun = ("route" if only_routes else "trail") + ("" if total == 1 else "s") 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 "", routes_list=routes_list) 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(official=not only_routes)} {list_head()}{lists}{empty}
    """) # A map of a selection is drawn only when it has at least this many tracks. MAP_MIN = 3 def overview_map(recs, label, *, wide=False, scope=""): """The map of the given trails' tracks (the overview geometry, limited to their ids unless every trail is shown). "" when none of them has a track.""" ids = [r["id"] for r in recs if "line" in r["derived"]["files"]] if not ids: return Markup('

    None of these trails has a GPX here, so there is no track to draw. ' 'Each trail’s page says where to get one.

    ') if len(ids) < MAP_MIN and scope != "all": names = words.join_names(f'{common.name(r)}' for r in recs if r["id"] in ids) return Markup(f'

    Only {names} {"has" if len(ids) == 1 else "have"} a GPX here, ' 'so no map of them all is drawn. Each trail’s page says where to get a track.

    ') ids_attr = "" if scope == "all" else f' data-ids="{esc(" ".join(ids))}"' n = len(ids) return Markup(f"""

    The map needs JavaScript. The list has every trail.

    • {common.SWATCH_LINE}Official trail
    • {common.SWATCH_ROUTE}Route

    {n} track{"s" if n != 1 else ""}, simplified for display. Select one for its name. Each trail’s page names its source, credit and licence. Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.

    """) def lists_row(records): """The ready-made lists, as a row of links with their counts. The terrain lists are on /lists/; here the Terrain filter does the same work.""" items = "".join( f'
  • {esc(lst.title)} {len(recs)}
  • ' for lst, recs in browse.shown(records) if not lst.key.startswith("terrain-")) if not items: return "" return f"""""" def render(records, site): """The home page body (HTML).""" c = counts(records) recs = sorted(records, key=sort_name) total = c["total"] lede = (f"{total} long-distance trails in the United States and Canada. Narrow them by where they are, " f"how long they take, when to walk them and what the country is like. " f"{c['gpx_here']} have a GPX to download.") contribute = "" if site.repo_url: contribute = (f'

    Something wrong, or a trail missing? ' f'Report a problem or ' f'suggest a trail.

    ') return f"""

    Find a long trail

    {lede}

    {lists_row(records)}

    Every trail

    {finder_form(records, c, length_steps(records))}
    {overview_map(records, "Map of the trails the filters leave", wide=True, scope="all")} {results(recs, finder=True)}

    Not for navigation: tracks vary in quality and some trails are unfinished. Check each trail’s own maps before you go.

    {contribute}
    """