"""One page per record: /trails//. The main sections say what the record says, in plain words. Every field of the record, with its exact value, is in the table at the end of the page (raw_record); the main flow carries no coded values. """ import os import re import urllib.parse from . import common, words from .markup import Markup, esc EXTRACT_SOURCES = {"osm": "OpenStreetMap", "usfs": "USDA Forest Service", "nps": "National Park Service"} GAUGE_MIN, GAUGE_MAX, GAUGE_LIMIT = -40.0, 40.0, common.LENGTH_LIMIT # Download formats in the order a hiker most likely wants them: GPX for devices first. FORMAT_ORDER = ("GPX", "GeoJSON") # Small building blocks ------------------------------------------------------ def code(value): return Markup(f'{esc(value)}') def fact(label, value, note=""): """One label/value row of a facts list. note: smaller text under the value. Plain-string values and notes are record text: escaped, with `backticked` spans set as code. """ value_html = value if isinstance(value, Markup) else common.rich(value) note_html = f"{note if isinstance(note, Markup) else common.rich(note)}" if note else "" return Markup(f"
{esc(label)}
{value_html}{note_html}
") def facts(*rows): rows = [r for r in rows if r] return Markup('
' + "".join(rows) + "
") if rows else Markup("") def ext_link(url, text=None): return Markup(f'{esc(text or url)}') def host(url): netloc = urllib.parse.urlsplit(url).netloc return netloc[4:] if netloc.startswith("www.") else netloc def yes_no(value): return "Yes" if value else "No" def block(id_, title, content, extra=""): """A section of the main column. Its heading carries the id; the section is not a landmark (no aria-labelledby): a page has many of them.""" return Markup(f'
' f'

{esc(title)}{extra}

{content}
') def record_text(text, cls=""): return Markup(f'

{common.rich(text)}

') def restates_no_line(value): """True for record values that only say there is no track ("none (no line included)").""" text = str(value or "").strip().lower() return text.startswith(("none (no line", "no line included", "no line to measure", "none (no track", "no track included", "no track to measure")) def region_names(rec): """The regions for the title block, each linked to its region page.""" regions = rec.get("regions", []) if len(regions) <= 3: parts = [] for code_ in regions: if code_ == words.ALL_CANADA: href = "/regions/#canada-wide" else: href = f"/regions/{words.region_key(code_, rec['country']).lower()}/" parts.append(f'{esc(words.region_name(code_))}') return Markup(", ".join(parts)) return common.regions_html(rec, linked=True) _ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)") def org_name(text): """The organisation or person a record names, without the record's own remarks: "Green Mountain Club (publishes the trail); its ArcGIS ..." -> "Green Mountain Club".""" name = _ORG_CUT.split(text or "", maxsplit=1)[0].strip() return name[:1].upper() + name[1:] # Page head ------------------------------------------------------------------ def page_head(rec): route = common.is_route(rec) country = words.COUNTRIES.get(rec["country"], rec["country"]) crumbs = [f'
  • Trails
  • ', f'
  • {esc(country)}
  • '] if route: crumbs.append('
  • Person-defined routes
  • ') crumbs.append(f'
  • {common.name(rec)}
  • ') if route: r = rec["route"] lead = "By " + r["creator"] + (f", {r['year']}" if r.get("year") else "") else: lead = rec.get("designation", "") sub = f'{esc(lead)} · {region_names(rec)}, {esc(country)}' has_plate = bool(common.shield_url(rec)) plate = common.plate(rec, size="lg", link=True, eager=True) if has_plate else "" return f"""
    {plate}

    {common.tags(rec)}

    {common.name(rec)} {esc(rec.get("short_name", ""))}

    {sub}

    {tally(rec)}
    """ def tally(rec): v = rec.get("verification", {}) note = rec.get("length_note", "") if note.replace(",", "") in (f"{rec['length_km']} km", f"{rec['length_km']} km published"): note = "" # the note only repeats the number items = [("Published length", words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]), note)] if v.get("verified") and "measured_km" in v: diff = v.get("difference_percent", 0) items.append(("Measured track", words.length(v["measured_km"], "stack", measured=True), f"{words.fmt_percent(diff)} against published")) else: items.append(("Measured track", Markup('Not measured'), "No track was downloaded and measured")) if common.has_line(rec): text = "In the dataset, partial" if common.line_short(rec) else "In the dataset" link = Markup(f'{esc(text)}') if rec["derived"].get("downloads") else text items.append(("Track", link, "Licence: " + common.licence_label(rec))) else: items.append(("Track", "Record only", "The reason is given below")) if common.is_route(rec): p = common.policy(rec) items.append(("Track policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p))) else: t = rec.get("tier", "") items.append(("Tier", words.label(words.TIERS, t), words.meaning(words.TIERS, t))) cells = "".join(f'
    {esc(a)}
    {esc(b)}{f"{esc(c)}" if c else ""}
    ' for a, b, c in items) return Markup(f'
    {cells}
    ') # Map or empty frame --------------------------------------------------------- def map_figure(rec): src = rec["source"] has_alt = "alternates" in rec["derived"]["files"] route = common.is_route(rec) legend = f'
  • {common.SWATCH_ROUTE if route else common.SWATCH_LINE}Main track
  • ' if has_alt: legend += f"
  • {common.SWATCH_ALT}Alternates and connectors
  • " bbox = rec["derived"].get("map_bbox") or rec["derived"].get("bbox") bbox_attr = f' data-bbox="{",".join(str(v) for v in bbox)}"' if bbox else "" credit = common.sentence(common.credit_text(src.get("attribution", ""))) return f"""

    The map needs JavaScript. Download the GPX or GeoJSON file from this page.

      {legend}

    Track: {esc(src.get("line_source", ""))}, read {esc(src.get("source_checked", ""))}, drawn simplified to 30 m. Credit: {esc(credit)} Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.

    """ def free_guides(rec): return [g for g in rec.get("guide", []) if g.get("access") == "free"] def empty_frame(rec): src = rec["source"] reason = src.get("line_absent_reason", "") actions = [] if common.is_route(rec): p = common.policy(rec) titles = { "open": "Get the track from the creator", "sold": "The track is sold as a guide", "withheld": "The creator does not publish a track", "unclear": "Whether the track may be shared is not settled", } title = titles.get(p, "No track in this dataset") rule = words.POLICIES.get(p, ("", "", ""))[2] if p == "open" and free_guides(rec): g = free_guides(rec)[0] actions.append(f'' f'{esc(g["title"])} {common.ICON_EXTERNAL}') if not actions: actions.append('See where to get the route') elif len(rec.get("guide", [])) > 1: actions.append('All guides') else: title = "No track in this dataset" reason = common.absent_reason_short(rec) rule = "A trail may be listed as a record only, with no track, when no track for it may be shared. The record says why." if src.get("publisher_url"): actions.append(f'' f'Publisher’s page {common.ICON_EXTERNAL}') elif src.get("url"): actions.append(f'' f'The source {common.ICON_EXTERNAL}') actions_html = f'

    {"".join(actions)}

    ' if actions else "" return f"""

    Record only

    {esc(title)}

    {common.rich(reason)}

    {esc(rule)}

    {actions_html}

    No map is drawn: the dataset holds no track for this {"route" if common.is_route(rec) else "trail"}, and does not guess one.

    """ # Aside: downloads, guides, links -------------------------------------------- def ordered_downloads(items): """GPX first, then GeoJSON, then anything else, each keeping its order.""" rank = {f: i for i, f in enumerate(FORMAT_ORDER)} return sorted(items, key=lambda d: rank.get(d["format"], len(rank))) def download_group(rec, label, swatch, note, items, gid): """One group of download buttons. GPX comes first and is the primary button. Each link's accessible name starts with the group: "Main track: GPX, 1.1 MB".""" buttons = "".join( f'' f'{common.ICON_DOWNLOAD}{esc(label)}: {esc(d["format"])}, ' f'{esc(words.fmt_bytes(d["bytes"]))}' for d in ordered_downloads(items)) return f"""
  • {swatch}{esc(label)}{esc(note)}

    {buttons}
  • """ def partial_notice(rec): """The notice above the buttons when the track differs from the published length by more than 15%: the record's own numbers, then its length_gap_note.""" if not common.line_differs(rec): return "" v = rec["verification"] diff = v["difference_percent"] head = "Partial track" if diff < 0 else "Longer than the published length" gap = rec["source"].get("length_gap_note", "") return f"""

    {head}

    The track in the dataset measures {esc(words.fmt_km1(v["measured_km"]))} km against a published {esc(words.fmt_km(rec["length_km"]))} km ({esc(words.fmt_percent(diff))}).

    {f"

    {common.rich(gap)}

    " if gap else ""}
    """ def downloads_panel(rec): downloads = rec["derived"].get("downloads", []) if not downloads: return "" src = rec["source"] v = rec.get("verification", {}) groups = [] main = [d for d in downloads if d["role"] == "main"] if main: note = f"{src.get('line_source', '')}" if v.get("verified") and "measured_km" in v: parts = v.get("parts") note = (f"{words.fmt_km1(v['measured_km'])} km measured" + (f" in {parts} part{'s' if parts != 1 else ''}" if parts else "") + f" · {note}") groups.append(download_group(rec, "Main track", common.SWATCH_ROUTE if common.is_route(rec) else common.SWATCH_LINE, note, main, "dl-main")) alts = [d for d in downloads if d["role"] == "alternates"] if alts: groups.append(download_group(rec, "Alternates and connectors", common.SWATCH_ALT, "Served separately by the source", alts, "dl-alt")) for i, d in enumerate(d for d in downloads if d["role"] == "extract"): key = d["file"][len(rec["id"]) + 1:-len(".geojson")] name = EXTRACT_SOURCES.get(key, key) # No swatch: extracts are not drawn on the map. groups.append(download_group(rec, f"Extract: {name}", "", "The track as this source serves it, before the sources were combined", [d], f"dl-x{i}")) licence = src.get("licence", "") licence_html = esc(words.label(words.LICENCES, licence)) if licence in words.LICENCE_URLS: licence_html = ext_link(words.LICENCE_URLS[licence], words.label(words.LICENCES, licence)) if "ODbL" in src.get("attribution", "") and licence != "ODbL-1.0": licence_html = Markup(f'{licence_html}; OpenStreetMap parts {ext_link(words.LICENCE_URLS["ODbL-1.0"], "ODbL 1.0")}') osm_note = ("

    Tracks from OpenStreetMap need the credit “© OpenStreetMap contributors” " "and stay under the ODbL (share-alike).

    ") if "ODbL" in src.get("attribution", "") + licence else "" release = (f'

    release.txt: ' f"the source, licence and date the track files came from.

    " if rec["derived"].get("release") else "") return f"""

    Download GPX and GeoJSON

    {partial_notice(rec)}

    GPX is simplified to 5 m for devices. GeoJSON is the full-resolution track as published in this dataset. Neither carries elevation.

      {"".join(groups)}

    Credit the source

    {esc(common.credit_text(src.get("attribution", "")))}

    Licence: {licence_html}

    {osm_note}
    {release}
    """ def guide_card(g, i): rows = [fact("Author", g.get("author", ""))] if g.get("publisher"): rows.append(fact("Publisher", g["publisher"])) if g.get("isbn"): rows.append(Markup(f'
    ISBN
    {esc(g["isbn"])}
    ')) rows.append(fact("Format", g.get("format", ""))) if g.get("price"): rows.append(fact("Price", g["price"], f"As the page stated it on {g.get('price_checked', '')}" if g.get("price_checked") else "")) access = g.get("access", "") return f"""
  • {esc(words.ACCESS.get(access, access))}

    {esc(g.get("title", ""))}

    {facts(*rows)} Guide page on {esc(host(g.get("url", "")))} {common.ICON_EXTERNAL}
  • """ def guides_panel(rec): guides = rec.get("guide", []) if not guides: return "" cards = "".join(guide_card(g, i) for i, g in enumerate(guides, 1)) return f"""

    Where to get the route

      {cards}

    Links go to the creator’s or publisher’s own page for each guide.

    """ def _is_url(value): return isinstance(value, str) and value.startswith(("http://", "https://")) def links_panel(rec): """Every link the record holds, each titled with the organisation or person the record names for it, with the host name and what the link is as secondary text.""" src = rec["source"] osm = rec.get("osm", {}) sh = rec.get("shield", {}) publisher = org_name(src.get("publisher", "")) items = {} # url -> [title, [what it is, ...]]; one entry per URL, titled by its first use def add(url, title, what): if url in items: items[url][1].append(what) else: items[url] = [title, [what]] kind = "route" if common.is_route(rec) else "trail" if src.get("publisher_url"): add(src["publisher_url"], publisher or host(src["publisher_url"]), f"The publisher's page for the {kind}") if osm.get("relation"): add(f"https://www.openstreetmap.org/relation/{osm['relation']}", f"OpenStreetMap relation {osm['relation']}", f"The {kind} as mapped in OpenStreetMap") if src.get("url"): what = "Where the included track came from" if common.has_line(rec) else "Where to ask for the track" title = "OpenStreetMap" if host(src["url"]).endswith("openstreetmap.org") else (publisher or host(src["url"])) add(src["url"], title, what) for g in rec.get("guide", []): if g.get("url") in items: add(g["url"], "", "A guide to the route") words_url = rec.get("route", {}).get("creator_words_url") if words_url: by = rec["route"].get("creator_words_by") or rec["route"].get("creator", "") add(words_url, by or host(words_url), "Where the quoted words were read") if _is_url(sh.get("logo_source")): owner = sh.get("logo_owner") or sh.get("contact") or host(sh["logo_source"]) add(sh["logo_source"], owner, "The page the logo was taken from") add(f"/trails/{rec['id']}/trail.toml", "trail.toml", "The record itself, as data") if rec["derived"].get("release"): add(f"/trails/{rec['id']}/release.txt", "release.txt", "Source, licence and date of the track files") def describe(url, whats): text = "; ".join([whats[0]] + [w[:1].lower() + w[1:] for w in whats[1:]]) return f"{host(url)} · {text}" if _is_url(url) else text lis = "".join(f'
  • {ext_link(u, t)}{esc(describe(u, w))}
  • ' for u, (t, w) in items.items()) return f"""
    """ # Main column ---------------------------------------------------------------- def policy_scale(current): items = [] for p in ("open", "sold", "withheld", "unclear"): lab, short, rule = words.POLICIES[p] here = ' aria-current="true"' if p == current else "" mark = 'This route' if p == current else "" items.append(f'{common.policy_chip(p)}{esc(short)}. {esc(rule)}{mark}') return Markup(f'
      {"".join(items)}
    ') def route_block(rec): r = rec["route"] p = r.get("line_policy", "") rows = [ fact("Creator", r.get("creator", "")), fact("First published", str(r["year"])) if r.get("year") else fact("First published", "Not recorded", "No page read states a year"), fact("Track policy", words.label(words.POLICIES, p), words.meaning(words.POLICIES, p)), ] quote = "" if r.get("creator_words"): by = r.get("creator_words_by") or r.get("creator", "") not_creator = ('Not the creator’s words' if r.get("creator_words_by") else 'The creator’s words') url = r.get("creator_words_url", "") quote = f"""

    {esc(r["creator_words"])}

    {esc(by)} {not_creator}

    {f'

    Read on {ext_link(url)}.

    ' if url else ""}
    """ note = f'

    About the route

    {record_text(r["note"])}' if r.get("note") else "" return block("route-title", "The route", facts(*rows) + Markup(quote) + policy_scale(p) + Markup(note)) def listing_note(rec): """The Listing row's note. A held record is listed but not settled; its wave_note (quoted, never paraphrased) says what. Other records show their wave_note as it is.""" wave = str(rec.get("wave", "")) note = rec.get("wave_note", "") if wave != "held": return note or words.meaning(words.WAVES, wave) meaning = words.meaning(words.WAVES, wave) if note: return Markup(f"{esc(meaning)}. The record’s note: “{common.rich(note)}”") return f"{meaning}. The record has no note saying what." def record_block(rec): k = common.kind(rec) tier = rec.get("tier", "") wave = str(rec.get("wave", "")) country = words.COUNTRIES.get(rec["country"], rec["country"]) names = ", ".join(words.region_name(c) for c in rec.get("regions", []) if c != words.ALL_CANADA) names_html = f' ({esc(names)})' if names else "" where = Markup(f'{common.regions_html(rec, linked=True)}{names_html}, {esc(country)}') rows = [ fact("Kind", words.label(words.KINDS, k), words.meaning(words.KINDS, k)), fact("Designation", rec.get("designation", "")), fact("Tier", words.label(words.TIERS, tier), words.meaning(words.TIERS, tier)), fact("Listing", words.label(words.WAVES, wave), listing_note(rec)), ] if rec.get("inclusion"): inc = rec["inclusion"] rows.append(fact("Inclusion", words.label(words.INCLUSION, inc), words.meaning(words.INCLUSION, inc))) rows += [ Markup(f'
    Where
    {where}
    '), Markup(f'
    Published length
    {words.length(rec["length_km"], "inline", rec["derived"]["length_mi"])}' f'{esc(rec.get("length_note", ""))}. A check value, not measured from the track.
    '), fact("Short name", rec.get("short_name", "")), fact("Record ID", Markup(code(rec["id"])), "Stable: the directory name, never changed"), ] return block("record-title", "The record", facts(*rows)) def gauge(diff): span = GAUGE_MAX - GAUGE_MIN pos = (min(max(diff, GAUGE_MIN), GAUGE_MAX) - GAUGE_MIN) / span * 100 off = "low" if diff < GAUGE_MIN else "high" if diff > GAUGE_MAX else "" inside = abs(diff) <= GAUGE_LIMIT side = "shorter than" if diff < 0 else "longer than" if diff > 0 else "the same as" label = (f"Measured track is {abs(diff):.1f} percent {side} the published length, " f"{'inside' if inside else 'outside'} the 15 percent limit.") mark_text = words.fmt_percent(diff) + (" (off the scale)" if off else "") ticks = (GAUGE_MIN, -GAUGE_LIMIT, 0, GAUGE_LIMIT, GAUGE_MAX) # placed by .gauge__tick--N in style.css scale = "".join(f'{esc(words.fmt_percent(v).replace(".0%", "%") if v else "0")}' for i, v in enumerate(ticks)) return Markup(f"""
    Within 15% of the published length Beyond 15%: the record must say why
    """) def verification_block(rec): v = rec.get("verification", {}) src = rec["source"] gap = src.get("length_gap_note", "") if gap and common.line_differs(rec) and rec["derived"].get("downloads"): # The download panel's notice carries the note, beside the files it is about. gap_html = '

    Why the lengths differ: see the notice in Download GPX and GeoJSON.

    ' elif gap: gap_html = f'

    Why the lengths differ

    {common.rich(gap)}

    ' else: gap_html = "" if v.get("verified") and "measured_km" in v: diff = v.get("difference_percent", 0) parts = v.get("parts") compare = f"""
    Published
    {words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}
    Measured
    {words.length(v["measured_km"], "stack", measured=True)}geodesic, from the track
    Difference
    {esc(words.fmt_percent(diff))}measured minus published
    Parts
    {esc(parts if parts is not None else "Not recorded")}pieces left after joining ends within 100 m
    """ content = Markup(compare) + gauge(diff) + record_text(v.get("note", "")) + Markup(gap_html) extra = Markup(f' Checked {esc(v.get("date", ""))}') if v.get("date") else "" verified_row = facts(fact("Measured", "Yes", "The track was downloaded and measured")) return block("verify-title", "Verification", verified_row + content, extra) if not common.has_line(rec) and restates_no_line(v.get("note", "")) and not gap: return "" # "No line to measure": the record only restates that there is no track rows = facts(fact("Measured", "No", "No track was downloaded and measured")) return block("verify-title", "Verification", rows + record_text(v.get("note", "")) + Markup(gap_html)) def source_block(rec): src = rec["source"] line = common.has_line(rec) status = src.get("status", "") licence = src.get("licence", "") licence_value = words.label(words.LICENCES, licence) licence_html = (ext_link(words.LICENCE_URLS[licence], licence_value) if licence in words.LICENCE_URLS else esc(licence_value)) source_help = 'Where to ask for the track: a layer or relation page' if line else "" def keep(value): """Rows of a record with no track are left out when they only restate that.""" return line or not restates_no_line(value) rows = [ fact("Track in this dataset", src.get("line_file"), "The main track file of the record") if line else "", fact("Source status", words.label(words.SOURCE_STATUS, status), words.meaning(words.SOURCE_STATUS, status)), fact("Publisher", src.get("publisher", "")), Markup(f'
    Publisher’s page
    {ext_link(src["publisher_url"])}
    ') if src.get("publisher_url") else "", Markup(f'
    Source
    {ext_link(src["url"])}{source_help}
    ') if src.get("url") else "", fact("Track source", src.get("line_source", "")) if keep(src.get("line_source")) else "", fact("Format", src.get("format", "")) if keep(src.get("format")) else "", fact("Main track", src.get("mainline", ""), "How the main track is told apart from alternates, connectors and side trails"), fact("Coordinates", src.get("crs", ""), "What the source stores; published files are longitude/latitude (EPSG:4326)") if line else "", Markup(f'
    Licence
    {licence_html}
    '), fact("Credit", common.credit_text(src.get("attribution", "")), "The credit line to show, as the source asks") if keep(src.get("attribution")) else "", fact("May be passed on", yes_no(src.get("redistributable")), "The source's terms allow its track to be passed on" if src.get("redistributable") else "The source's terms do not allow its track to be passed on") if line else "", fact("OpenStreetMap only", yes_no(src.get("osm_only")), "OpenStreetMap is the only source of the included track" if src.get("osm_only") else "") if line else "", fact("Source checked", src.get("source_checked", "")), fact("Newer release?", src["discovery"], "How to tell whether the source has a newer release") if src.get("discovery") else "", ] if src.get("decision") or src.get("decision_text"): rows.append(fact("Decision", src.get("decision_text", "") or words.DECISIONS.get(src.get("decision", ""), src.get("decision", "")))) licence_text = (f'

    What the source says

    {record_text(src["licence_text"])}' '

    With the page it was read on. Not legal advice.

    ') if src.get("licence_text") else "" return block("source-title", "Source and licence", facts(*rows) + Markup(licence_text)) def osm_block(rec): osm = rec.get("osm", {}) rel = osm.get("relation", 0) if rel: value = Markup(f'
    Relation
    {ext_link(f"https://www.openstreetmap.org/relation/{rel}", str(rel))}
    ') elif common.has_line(rec): value = fact("Relation", "None recorded", "No relation found, or not searched") else: value = "" # no line and no relation: nothing to say beyond the note return block("osm-title", "OpenStreetMap", facts(value, fact("Note", osm.get("note", "")))) def logo_block(rec): sh = rec.get("shield", {}) status = sh.get("status", "") if not common.shield_url(rec): # No logo file: one line, the status and the record's note. lead = {"no-logo-exists": "No logo", "logo-not-found": "Logo not found", "use-real-logo": "Logo not included"}.get(status, "No logo file") note = sh.get("note", "") return block("logo-title", "Logo", Markup( f'

    {esc(lead)}.{" " + common.rich(note) if note else ""}

    ')) rows = [ fact("Status", words.label(words.SHIELD_STATUS, status), words.meaning(words.SHIELD_STATUS, status)), fact("Holder", sh.get("logo_owner", "")) if sh.get("logo_owner") else "", fact("Contact", sh.get("contact", "")) if sh.get("contact") and sh.get("contact") != sh.get("logo_owner") else "", Markup(f'
    Taken from
    {ext_link(sh["logo_source"])}
    ') if _is_url(sh.get("logo_source")) else fact("Taken from", sh.get("logo_source") or "Not recorded"), fact("File", sh.get("logo_file", "")), fact("Note", sh.get("note", "")), ] federal = ("

    Some logos are official emblems of United States National Scenic or Historic Trails. " "Those emblems are federal insignia; their use here is for identification only.

    " if rec.get("tier") == "national" or "National Historic Trail" in rec.get("designation", "") else "") notice = f"""

    Shown only to identify the trail

    This logo belongs to {esc(sh.get("logo_owner", "its holder"))}. It is not covered by this dataset’s licences, and no right to use it for any other purpose is given or implied.

    {federal}

    A holder who wants a logo removed, replaced or credited differently can ask; see Logos.

    """ return block("logo-title", "Logo", Markup(notice) + facts(*rows)) def correction_block(rec, site): parts = [] if common.is_route(rec): parts.append(f"""

    If you made this route

    A route’s creator can ask for its record to be corrected or removed, and the record will be corrected or removed. Say which route: {code(rec["id"])}. See About.

    """) if site.issues_url: parts.append(f"""

    Found an error? Open an issue with the record ID ({code(rec["id"])}), what is wrong, and where the correct information can be checked: a source page, a map, or a measured line.

    """) if not parts: return "" return block("correct-title", "Corrections", Markup("".join(parts))) def flatten(obj, prefix=""): """(field, value) for every leaf of a record: "source.licence", "guide[0].title", "regions[1]".""" if isinstance(obj, dict): for k, v in obj.items(): yield from flatten(v, f"{prefix}.{k}" if prefix else k) elif isinstance(obj, list): for i, v in enumerate(obj): yield from flatten(v, f"{prefix}[{i}]") else: yield prefix, obj def raw_value(value): """A value as the record stores it: true/false, numbers as written, "" for an empty string.""" if isinstance(value, bool): return "true" if value else "false" if isinstance(value, str): return value if value else '""' return str(value) def raw_record(rec): """Every field of the record with its exact value, as the last block of the page.""" fields = {k: v for k, v in rec.items() if k != "derived"} rows = "".join(f'{esc(field)}{esc(raw_value(value))}' for field, value in flatten(fields)) return Markup(f"""
    Every field of the record, with its exact value

    As stored in trail.toml. The record schema says what each field means.

    {rows}
    FieldValue
    """) # The page ------------------------------------------------------------------- def description(rec): km = words.fmt_km(rec["length_km"]) mi = words.fmt_int(rec["derived"]["length_mi"]) where = ", ".join(words.region_name(c) for c in rec.get("regions", [])[:3]) if len(rec.get("regions", [])) > 3: where += " and more" kind = "person-defined route" if common.is_route(rec) else "long trail" text = f"{rec['name']}: a {km} km ({mi} mi) {kind} in {where}. " if common.has_line(rec): text += "Download its track as GPX or GeoJSON, with the source, licence and credit." else: text += "Record only: " + common.absent_reason_short(rec) return text if len(text) <= 300 else text[:297].rsplit(" ", 1)[0] + "…" def render(rec, site): """Return (title, description, body HTML, needs_map) for one record.""" has_map = common.has_line(rec) aside = downloads_panel(rec) + guides_panel(rec) + links_panel(rec) main = (route_block(rec) if common.is_route(rec) else "") + record_block(rec) + verification_block(rec) \ + source_block(rec) + osm_block(rec) + logo_block(rec) + correction_block(rec, site) + raw_record(rec) body = f"""{page_head(rec)}
    {map_figure(rec) if has_map else empty_frame(rec)}
    {main}
    """ return rec["name"], description(rec), body, has_map def release_path(repo_root, rec): path = os.path.join(repo_root, rec["id"], "release.txt") return path if os.path.isfile(path) else ""