Put miles and feet first, and give the site a proper mark
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

Units. Miles and feet now come first everywhere unless the reader
chooses kilometres and metres: paired figures, the time estimate, the
elevation profile, page descriptions and the map scale. The length
filter and the length scale use round mile steps (round kilometre steps
for a reader who chose them). The lists defined by length are now
"Under 100 miles" and "The longest" at 1,000 miles or more; the old
/lists/under-100-km/ address redirects. The records stay metric.

Branding. The tab icon was a bare red blaze that read as a red block;
it is now a mountain with a trail up it, with PNG sizes for browsers
and phones that need them. The home page opens with the mark, the name
and what the site offers. Link previews get a real 1200x630 image:
the old one was an SVG, which Reddit, Slack and iMessage do not draw.

The decorative contour lines now stay inside the content column and
thin out to nothing on every side, where they used to run to the right
edge of a wide window and stop dead at the bottom of the band.

Tests updated for the new trail counts.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-14 20:37:14 -07:00
1 parent c7e8e58dce
commit 19fabadd49
27 files changed
+480 -189

No files matched your search

+11 -7
View File
@@ -20,8 +20,12 @@ from . import common, facets, words
MIN_SIZE = 4
MAX_SHARE = 0.75
LONG_KM = 2000
SHORT_KM = 100
# The two lists defined by length are set in miles; membership compares the
# record's kilometres with the mile figure converted once, here.
LONG_MI = 1000
SHORT_MI = 100
LONG_KM = LONG_MI * words.KM_PER_MI
SHORT_KM = SHORT_MI * words.KM_PER_MI
@dataclass(frozen=True)
@@ -35,8 +39,8 @@ class List:
sort: str = "name"
def _mi(km):
return words.fmt_int(words.km_to_mi(km))
def _km(mi):
return words.fmt_int(mi * words.KM_PER_MI)
def _band(key):
@@ -50,10 +54,10 @@ LISTS = (
List("routes", "Routes", facets.ROUTE_DEFINITION,
lambda r: facets.kind(r) == "route"),
List("longest", "The longest",
f"Trails of {LONG_KM:,} km ({_mi(LONG_KM)} mi) or more.",
f"Trails of {LONG_MI:,} miles ({_km(LONG_MI)} km) or more.",
lambda r: r["length_km"] >= LONG_KM, sort="length-desc"),
List("under-100-km", f"Under {SHORT_KM} km",
f"Trails shorter than {SHORT_KM} km ({_mi(SHORT_KM)} mi).",
List("under-100-miles", f"Under {SHORT_MI} miles",
f"Trails shorter than {SHORT_MI} miles ({_km(SHORT_MI)} km).",
lambda r: r["length_km"] < SHORT_KM, sort="length-asc"),
List("a-week-or-less", "A week or less",
"Trails most people walk in a week or less, as a source states it or as estimated from the length.",
+4 -3
View File
@@ -42,11 +42,12 @@ def line_short(rec):
def partial_short_text(rec):
"""The short form for lists: "Track measures 2.0 km of 1,100 km published"."""
"""The short form for lists: "Track measures 1.2 mi (2.0 km) of 684 mi (1,100 km) published",
in the reader's unit order (words.length). Markup."""
v = rec["verification"]
word = "of" if v["difference_percent"] < 0 else "against"
return (f"Track measures {words.fmt_km1(v['measured_km'])} km {word} "
f"{words.fmt_km(rec['length_km'])} km published")
return Markup(f"Track measures {words.length(v['measured_km'], measured=True)} {word} "
f"{words.length(rec['length_km'], mi=rec['derived']['length_mi'])} published")
def name(rec):
+2 -2
View File
@@ -335,11 +335,11 @@ site calls them trails.</p>
</section>
<section aria-labelledby="how-trails-are-chosen"><h2 id="how-trails-are-chosen">How trails are chosen</h2>
<p>A trail is listed when it is a named, continuous walk, or a named loop, of at least 80&nbsp;km (50&nbsp;miles)
<p>A trail is listed when it is a named, continuous walk, or a named loop, of at least 50&nbsp;miles (80&nbsp;km)
in the United States or Canada. It is either an official trail, looked after as one trail by a land agency or
a trail association, or a route: {esc(facets.ROUTE_DEFINITION[0].lower() + facets.ROUTE_DEFINITION[1:])}
{routes} of the {n} trails are routes. Every National Scenic Trail is listed, and a few well-known multi-day
trails between 60 and 80&nbsp;km.</p>
trails between 37 and 50&nbsp;miles (60 and 80&nbsp;km).</p>
<p>Each record has a <em>tier</em>, which says why it is listed. A record can also be <em>held</em>: listed,
but with something about it not yet settled, which its note says.</p>
<div class="table-wrap"><table><thead><tr><th scope="col">Tier</th><th scope="col">What it means</th><th scope="col">Records</th></tr></thead>
+5 -5
View File
@@ -123,12 +123,12 @@ def parts_caveat(elev):
def plain_elevation(m):
""""2,025 m (6,644 ft)", for a sentence or a text alternative."""
return f"{words.fmt_int(m)} m ({words.fmt_int(m / words.M_PER_FT)} ft)"
""""6,644 ft (2,025 m)", for a sentence or a text alternative."""
return f"{words.fmt_int(words.m_to_ft(m))} ft ({words.fmt_int(m)} m)"
def plain_length(km):
return f"{words.fmt_km1(km)} km ({words.fmt_int(words.km_to_mi(km))} mi)"
return f"{words.fmt_int(words.km_to_mi(km))} mi ({words.fmt_km1(km)} km)"
def is_sea_level(point):
@@ -204,7 +204,7 @@ LEFT, RIGHT, TOP, BOTTOM = 58, 14, 14, 40
def profile_svg(elev, loop=False):
"""The profile as inline SVG, drawn now, not by a script. Both unit systems
are drawn; CSS shows one, through the same len__km / len__mi pair and the
are drawn; CSS shows one, through the same len__mi / len__km pair and the
reader's unit preference as every length on the site."""
profile = elev.get("profile") or []
if len(profile) < 2:
@@ -283,4 +283,4 @@ def profile_svg(elev, loop=False):
return Markup(
f'<svg class="elev-profile" viewBox="0 0 {W} {H}" role="img" '
f'aria-label="{esc(summary_sentence(elev, loop))}" focusable="false">'
f"{axis_group('km')}{axis_group('mi')}{axes}{line}{marks}</svg>")
f"{axis_group('mi')}{axis_group('km')}{axes}{line}{marks}</svg>")
+4 -2
View File
@@ -21,6 +21,7 @@ import re
from functools import cmp_to_key
from . import common, elevation, hike, words
from .markup import Markup
# Facet names, exactly as every page shows them.
WHERE, LENGTH, TIME, SEASON, TERRAIN, KIND, WALKING, SHAPE, GPX = (
@@ -155,8 +156,9 @@ def estimate_note(rec):
if not time_days(rec)[2]:
return ""
slow, fast = pace(rec)
mi = f"{round(slow / words.KM_PER_MI)} to {round(fast / words.KM_PER_MI)} mi"
return f"Estimated from the length, at {slow} to {fast} km ({mi}) a day."
mi = f"{round(words.km_to_mi(slow))} to {round(words.km_to_mi(fast))} mi"
return Markup(f'Estimated from the length, at <span class="len len--inline"><span class="len__mi">{mi}</span>'
f'<span class="len__km">{slow} to {fast} km</span></span> a day.')
# Season ---------------------------------------------------------------------
+51 -26
View File
@@ -10,21 +10,40 @@ import math
from . import browse, common, 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)
# Length range choices for the filters, round in the unit they are written in.
# Miles come first (the shortest trails are about 40 miles, the longest over
# 6,000); a reader who chose kilometres gets round kilometre steps. length_steps()
# adds a top step above the longest trail, so a chosen upper bound can always
# reach every trail.
LENGTH_STEPS_MI = (50, 75, 100, 150, 200, 300, 500, 1000, 2000, 4000, 8000)
LENGTH_STEPS_KM = (60, 80, 100, 150, 200, 300, 500, 1000, 2000, 4000, 8000)
LENGTH_STEPS = LENGTH_STEPS_MI
def length_steps(records):
"""LENGTH_STEPS plus a round step at or above the longest trail, when that is longer."""
def length_steps(records, unit="mi"):
"""The round steps for the unit, 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 unit == "mi":
longest = words.km_to_mi(longest)
steps = list(LENGTH_STEPS_MI if unit == "mi" else LENGTH_STEPS_KM)
if longest > steps[-1]:
magnitude = 10 ** int(math.floor(math.log10(longest)))
steps.append(int(math.ceil(longest / magnitude) * magnitude))
return steps
def step_value(n, unit):
"""The option value of a length step: "100mi" or "160km". app.js reads it the same way."""
return f"{n}{unit}"
def step_label(n, unit):
""""100 mi · 161 km": the step in its own unit first."""
if unit == "mi":
return f"{n:,} mi &middot; {words.fmt_int(n * words.KM_PER_MI)} km"
return f"{n:,} km &middot; {words.fmt_int(words.km_to_mi(n))} mi"
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."""
@@ -95,7 +114,7 @@ def gpx_cell(rec):
route = facets.kind(rec) == "route"
if facets.gpx_here(rec):
swatch = common.SWATCH_ROUTE if route else common.SWATCH_LINE
partial = (f'<p class="entry__partial">{esc(common.partial_short_text(rec))}</p>'
partial = (f'<p class="entry__partial">{common.partial_short_text(rec)}</p>'
if common.line_differs(rec) else "")
return (f'<span class="line__status">{swatch}{esc(facets.GPX_SHORT[status])}</span>'
f'<span class="line__detail">GPX and GeoJSON</span>{partial}')
@@ -152,9 +171,8 @@ def entry(rec, *, level=3, extra="", routes_list=False):
# The filters ------------------------------------------------------------------
def _length_options(steps, selected_any_last):
opts = [f'<option value="{km}">{km:,} km &middot; {words.fmt_int(words.km_to_mi(km))} mi</option>'
for km in steps]
def _length_options(steps, selected_any_last, unit="mi"):
opts = [f'<option value="{step_value(n, unit)}">{step_label(n, unit)}</option>' for n in steps]
if selected_any_last:
return "".join(opts[1:]) + '<option value="" selected>Any</option>'
return '<option value="">Any</option>' + "".join(opts[:-1])
@@ -206,6 +224,7 @@ 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)
km_steps = length_steps(records, "km")
first, more = [], []
first.append(f"""<div class="field">
<label class="field__label" for="where">{facets.WHERE}</label>
@@ -215,10 +234,10 @@ def finder_form(records, c=None, steps=None):
<legend>{facets.LENGTH}</legend>
<div class="range">
<label class="vh" for="min">Shortest length</label>
<select class="select" id="min" name="min" data-length-options>{_length_options(steps, False)}</select>
<select class="select" id="min" name="min" data-length-options="min" data-steps-mi="{",".join(map(str, steps))}" data-steps-km="{",".join(map(str, km_steps))}">{_length_options(steps, False)}</select>
<span class="range__to" aria-hidden="true">to</span>
<label class="vh" for="max">Longest length</label>
<select class="select" id="max" name="max" data-length-options>{_length_options(steps, True)}</select>
<select class="select" id="max" name="max" data-length-options="max" data-steps-mi="{",".join(map(str, steps))}" data-steps-km="{",".join(map(str, km_steps))}">{_length_options(steps, True)}</select>
</div>
<p class="field__hint" id="len-hint" aria-live="polite">Any length.</p>
</fieldset>""")
@@ -292,8 +311,9 @@ def finder_form(records, c=None, steps=None):
# The list ---------------------------------------------------------------------
# The length strip's ticks (style.css .loglen): 100, 1,000 and 10,000 km.
SCALE_KM = (100, 1000, 10000)
# The length strip's ticks (style.css .loglen): 100, 1,000 and 10,000 miles, or
# kilometres for a reader who chose them. Positions are in style.css.
SCALE_TICKS = (100, 1000, 10000)
# Sort column of each sort key, and the arrow for its direction in the head.
@@ -326,11 +346,10 @@ def list_head(sort_key="name"):
"""
sort_key = facets.normalize_sort(sort_key)
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'<span><span class="len__km">{km:,}{unit}</span>'
f'<span class="len__mi">{words.fmt_int(words.km_to_mi(km))}{mi_unit}</span></span>')
for i, n in enumerate(SCALE_TICKS):
last = i == len(SCALE_TICKS) - 1
ticks.append(f'<span><span class="len__mi">{n:,}{" mi" if last else ""}</span>'
f'<span class="len__km">{n:,}{" km" if last else ""}</span></span>')
scale = f'<span class="list-head__scale">{"".join(ticks)}</span>'
return f"""<div class="list-head" aria-hidden="true">
{_head_button("name", "Trail", sort_key)}
@@ -344,8 +363,8 @@ def list_head(sort_key="name"):
UNITS_TOGGLE = """<fieldset class="results-units">
<legend class="vh">Lengths</legend>
<div class="seg seg--small">
<label><input type="radio" name="units-list" value="km" checked><span>km</span></label>
<label><input type="radio" name="units-list" value="mi"><span>mi</span></label>
<label><input type="radio" name="units-list" value="mi" checked><span>mi</span></label>
<label><input type="radio" name="units-list" value="km"><span>km</span></label>
</div>
</fieldset>"""
@@ -535,17 +554,23 @@ def render(records, site):
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.")
lede = (f"{total} trails. Narrow them by where they are, how long they take, when to walk them "
f"and what the country is like. {c['gpx_here']} have a GPX to download.")
contribute = ""
if site.repo_url:
contribute = (f'<p class="finder__foot">Something wrong, or a trail missing? '
f'<a href="{esc(site.correction_url())}">Report a problem</a> or '
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a>.</p>')
return f"""<section class="hero hero--short" aria-labelledby="hero-title">
return f"""<section class="hero hero--short hero--home" aria-labelledby="hero-title">
<div class="container hero__inner">
<h1 id="hero-title">Find a long trail</h1>
<h1 id="hero-title" class="lockup"><img class="lockup__mark" src="/assets/favicon.svg" alt="" width="96" height="96">{esc(site.name)}</h1>
<p class="hero__tagline">Long-distance hiking trails of the United States and Canada, to compare and download.</p>
<ul class="hero__tags">
<li><a href="#finder">Filters</a></li>
<li><a href="/lists/with-gpx/">GPX</a></li>
<li><a href="/sources/">A source for every fact</a></li>
<li><a href="/data/">Open data</a></li>
</ul>
<p class="hero__lede">{lede}</p>
{lists_row(records)}
</div>
+13 -7
View File
@@ -56,7 +56,7 @@ def header(path, site):
for text, href in NAV)
return Markup(f"""<header class="site-header">
<div class="container site-header__inner">
<a class="wordmark" href="/"><span class="wordmark__blaze" aria-hidden="true"></span>{esc(site.name)}</a>
<a class="wordmark" href="/"><img class="wordmark__mark" src="/assets/favicon.svg" alt="" width="28" height="28">{esc(site.name)}</a>
<nav aria-label="Main"><ul class="nav">{items}</ul></nav>
</div>
</header>""")
@@ -71,7 +71,7 @@ def footer(site):
return Markup(f"""<footer class="site-footer">
<div class="container site-footer__grid">
<div class="site-footer__about">
<a class="wordmark" href="/"><span class="wordmark__blaze" aria-hidden="true"></span>{esc(site.name)}</a>
<a class="wordmark" href="/"><img class="wordmark__mark" src="/assets/favicon.svg" alt="" width="28" height="28">{esc(site.name)}</a>
<p>Not for navigation: tracks vary in quality, some trails are unfinished, and some have no GPX here. Check a trail&rsquo;s own maps before you go.</p>
<p>The trail data is public domain (CC0-1.0). Each track keeps the terms of its source, named on its page. Tracks from OpenStreetMap are &copy;&nbsp;OpenStreetMap contributors, under the ODbL. Logos belong to their holders and are shown only to identify each trail.</p>
</div>
@@ -106,8 +106,8 @@ def footer(site):
<fieldset class="field">
<legend>Units</legend>
<div class="seg">
<label><input type="radio" name="units" value="km" checked><span>km and m first</span></label>
<label><input type="radio" name="units" value="mi"><span>mi and ft first</span></label>
<label><input type="radio" name="units" value="mi" checked><span>mi and ft first</span></label>
<label><input type="radio" name="units" value="km"><span>km and m first</span></label>
</div>
</fieldset>
</div>
@@ -154,19 +154,25 @@ def layout(title, body, *, path, description="", maps=False, scripts=(), data=No
f'<meta property="og:description" content="{esc(description)}">',
f'<meta property="og:type" content="{esc(og_type)}">',
f'<meta property="og:site_name" content="{esc(site.name)}">',
'<meta name="twitter:card" content="summary">',
'<meta name="twitter:card" content="summary_large_image">',
f'<meta name="twitter:title" content="{esc(full_title)}">',
f'<meta name="twitter:description" content="{esc(description)}">',
]
if canonical:
head.append(f'<meta property="og:url" content="{esc(canonical)}">')
head.append(f'<meta property="og:image" content="{esc(site.canonical("/assets/favicon.svg"))}">')
head.append(f'<meta name="twitter:image" content="{esc(site.canonical("/assets/favicon.svg"))}">')
# A PNG: link previews (Reddit, Slack, iMessage) do not draw an SVG.
image = esc(site.canonical("/assets/og.png"))
head.append(f'<meta property="og:image" content="{image}">')
head.append('<meta property="og:image:width" content="1200">')
head.append('<meta property="og:image:height" content="630">')
head.append(f'<meta name="twitter:image" content="{image}">')
if jsonld is not None:
head.append(str(_ld_json_block(jsonld)))
head += [
'<meta name="color-scheme" content="light dark">',
'<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml">',
'<link rel="icon" href="/assets/favicon-32.png" type="image/png" sizes="32x32">',
'<link rel="apple-touch-icon" href="/assets/apple-touch-icon.png">',
]
head += [f'<link rel="preload" href="{f}" as="font" type="font/woff2" crossorigin>' for f in FONT_PRELOADS]
if maps:
+2 -2
View File
@@ -2,7 +2,7 @@
import os
import tomllib
from . import elevation
from . import elevation, words
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SHIELD_NAMES = ("shield.svg", "shield.png")
@@ -50,7 +50,7 @@ def load_record(root, tid):
rec["derived"] = {
"kind": trail_kind(rec),
"has_line": bool(rec.get("source", {}).get("line_file")),
"length_mi": int(round(length_km / 1.609344)),
"length_mi": int(round(length_km / words.KM_PER_MI)),
"files": find_files(root, tid, rec),
"elevation": elevation.load_file(root, tid),
"status": trail_status(rec),
+6 -6
View File
@@ -509,7 +509,7 @@ def download_group(rec, label, swatch, note, items, gid):
f'<span class="button__meta">{esc(words.fmt_bytes(d["bytes"]))}</span></a>'
for d in ordered_downloads(items))
return f"""<li class="download">
<p class="download__what">{swatch}<strong id="{gid}">{esc(label)}</strong><small>{esc(note)}</small></p>
<p class="download__what">{swatch}<strong id="{gid}">{esc(label)}</strong><small>{note if isinstance(note, Markup) else esc(note)}</small></p>
<div class="download__files">{buttons}</div>
</li>"""
@@ -525,7 +525,7 @@ def partial_notice(rec):
gap = rec["source"].get("length_gap_note", "")
return f"""<div class="notice notice--partial">
<h3>{head}</h3>
<p>The track in the dataset measures {esc(words.fmt_km1(v["measured_km"]))}&nbsp;km against a published {esc(words.fmt_km(rec["length_km"]))}&nbsp;km ({esc(words.fmt_percent(diff))}).</p>
<p>The track in the dataset measures {words.length(v["measured_km"], measured=True)} against a published {words.length(rec["length_km"], mi=rec["derived"]["length_mi"])} ({esc(words.fmt_percent(diff))}).</p>
{f"<p>{common.rich(gap)}</p>" if gap else ""}
</div>"""
@@ -542,8 +542,8 @@ def downloads_panel(rec):
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}")
note = Markup(f"{words.length(v['measured_km'], measured=True)} measured"
+ esc((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"]
@@ -859,7 +859,7 @@ def elevation_block(rec):
"No climb is counted across a gap."),
]
if starts:
rows.append(fact("Part starts", ", ".join(words.fmt_km1(s) for s in starts) + " km",
rows.append(fact("Part starts", words.distances(starts),
"The distance along the profile where each part after the first begins"))
if not elevation.show_profile(elev):
rows.append(fact("Profile", "Not drawn", elevation.parts_caveat(elev)))
@@ -1096,7 +1096,7 @@ def description(rec):
else:
km = words.fmt_km(rec["length_km"])
mi = words.fmt_int(rec["derived"]["length_mi"])
text = f"{rec['name']}: a {kind_word(rec)} of {km} km ({mi} mi) {place_text(rec)}."
text = f"{rec['name']}: a {kind_word(rec)} of {mi} mi ({km} km) {place_text(rec)}."
text += (" Download its GPX here." if common.has_line(rec)
else " Where to get its GPX.")
return text if len(text) <= 300 else text[:297].rsplit(" ", 1)[0] + "…"
+25 -11
View File
@@ -33,8 +33,8 @@ ALL_CANADA = "all provinces and territories"
# (label, meaning). Meanings follow docs/schema.md and README.md.
TIERS = {
"national": ("National Scenic Trail", "A United States National Scenic Trail"),
"regional": ("Regional", "A long trail of 80 km (50 mi) or more"),
"short": ("Short", "A well-known multi-day trail of 60 to 80 km"),
"regional": ("Regional", "A long trail of 50 miles (80 km) or more"),
"short": ("Short", "A well-known multi-day trail of 37 to 50 miles (60 to 80 km)"),
"deferred": ("Deferred", "Listed, but something about it is not settled; the record's note says what"),
"candidate": ("Candidate", "Listing not yet decided"),
}
@@ -152,6 +152,10 @@ def km_to_mi(km):
return km / KM_PER_MI
def m_to_ft(m):
return m / M_PER_FT
def fmt_percent(p):
"""-2.5 -> "−2.5%" (true minus sign), 0.9 -> "+0.9%", 0 -> "0.0%"."""
if p == 0:
@@ -169,17 +173,27 @@ def fmt_bytes(n):
def length(km, style="inline", mi=None, measured=False):
"""A length in both units. The reader's unit preference decides the order (CSS).
"""A length in both units. Miles come first unless the reader chose kilometres (CSS).
style "inline": "1,287 km (800 mi)"; "stack": large first unit over small second.
style "inline": "800 mi (1,287 km)"; "stack": large first unit over small second.
measured: a measured length, always written with its one decimal ("2.0 km").
"""
mi = km_to_mi(km) if mi is None else mi
km_text = f"{fmt_km1(km) if measured else fmt_km(km)} km"
whole = float(km).is_integer() and not measured
mi_text = f"{fmt_int(mi)} mi" if whole or mi >= 100 else f"{mi:,.1f} mi"
return Markup(f'<span class="len len--{style}"><span class="len__km">{esc(km_text)}</span>'
f'<span class="len__mi">{esc(mi_text)}</span></span>')
return Markup(f'<span class="len len--{style}"><span class="len__mi">{esc(mi_text)}</span>'
f'<span class="len__km">{esc(km_text)}</span></span>')
def distances(kms):
"""Several measured distances in both units, as lengths are: "0.0, 12.4 mi" with "0.0, 20.0 km"
behind it, the reader's order decided by CSS. Markup."""
kms = list(kms)
mi = ", ".join(f"{km_to_mi(k):,.1f}" for k in kms) + " mi"
km = ", ".join(fmt_km1(k) for k in kms) + " km"
return Markup(f'<span class="len len--inline"><span class="len__mi">{esc(mi)}</span>'
f'<span class="len__km">{esc(km)}</span></span>')
# Hiker facts ([hike] table) -------------------------------------------------
@@ -228,12 +242,12 @@ def fmt_days(days):
def elevation(m, style="inline"):
"""An elevation in metres and feet; the reader's unit preference decides the order,
with the same len__km / len__mi pair as lengths: "2,025 m (6,644 ft)".
"""An elevation in feet and metres; feet come first unless the reader chose metres,
with the same len__mi / len__km pair as lengths: "6,644 ft (2,025 m)".
style "stack" sets the first unit large over the second, as lengths do."""
ft = m / M_PER_FT
return Markup(f'<span class="len len--{style}"><span class="len__km">{esc(fmt_int(m))} m</span>'
f'<span class="len__mi">{esc(fmt_int(ft))} ft</span></span>')
ft = m_to_ft(m)
return Markup(f'<span class="len len--{style}"><span class="len__mi">{esc(fmt_int(ft))} ft</span>'
f'<span class="len__km">{esc(fmt_int(m))} m</span></span>')
def join_names(names):