Make track clicks land, open the data files to other sites, and tidy descriptions, redirects and printing

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 12:03:54 -07:00
1 parent f2235c420d
commit 0e8b5c8ca4
93 files changed
+623 -96

No files matched your search

+30 -18
View File
@@ -98,10 +98,30 @@ _DANGLING = {"and", "or", "but", "nor", "with", "to", "of", "the", "a", "an", "i
_ABBREVIATIONS = {"st", "mt", "mts", "ft", "no", "vs", "u.s", "d.c", "dr", "jr", "sr", "approx", "e.g", "i.e"}
def cut_clean(text, limit):
"""text if it fits, else cut at the end of a word within limit characters and closed with a
full stop, never with an ellipsis: a cut never leaves a comma, a colon or a conjunction (or other
joining word) last."""
text = re.sub(r"\s+", " ", text).strip()
if len(text) <= limit:
return text
head = text[:limit - 1]
if text[limit - 1] != " ":
head = head.rsplit(" ", 1)[0] if " " in head else head
head = head.rstrip(" ,;:.")
while True:
word = head.rsplit(" ", 1)[-1].lower().rstrip(",;:")
if " " in head and (word in _DANGLING or head[-1] in ",;:"):
head = head.rsplit(" ", 1)[0].rstrip(" ,;:.")
else:
break
return head + "."
def share_description(text, limit=SHARE_DESCRIPTION_LIMIT):
"""text for a social preview: at most `limit` characters, cut from the search description at the
end of a sentence where one falls past half the limit, else at the end of a word, with an
ellipsis. A cut never leaves a comma, a colon or a conjunction (or other joining word) last."""
end of its last whole sentence that fits (one past a quarter of the limit), else at the end of a
word, closed with a full stop (cut_clean). Never an ellipsis."""
text = re.sub(r"\s+", " ", text).strip()
if len(text) <= limit:
return text
@@ -113,19 +133,9 @@ def share_description(text, limit=SHARE_DESCRIPTION_LIMIT):
if last in _ABBREVIATIONS:
continue
best = m.end()
if best >= limit // 2:
if best >= limit // 4:
return text[:best]
head = text[:limit - 1]
if text[limit - 1] != " ":
head = head.rsplit(" ", 1)[0] if " " in head else head
head = head.rstrip(" ,;:.")
while True:
word = head.rsplit(" ", 1)[-1].lower().rstrip(",;:")
if " " in head and (word in _DANGLING or head[-1] in ",;:"):
head = head.rsplit(" ", 1)[0].rstrip(" ,;:.")
else:
break
return head + "\u2026"
return cut_clean(text, limit)
def plain_name(rec):
@@ -265,9 +275,11 @@ def policy_chip(value):
f'<span class="vh">Track policy: </span>{esc(lab)}</span>')
def logo_img(rec, alt, eager=False):
"""The logo <img>: the PNG thumbnail at its real size when there is one (olt/thumbs.py), else the file."""
logo = rec["derived"].get("logo_img")
def logo_img(rec, alt, eager=False, listed=False):
"""The logo <img>: the PNG thumbnail at its real size when there is one (olt/thumbs.py), else the file.
listed: the list-size thumbnail (twice the size a list shows a logo at), when there is one."""
logo = (rec["derived"].get("list_img") if listed else None) or rec["derived"].get("logo_img")
src, dims = (logo["src"], f' width="{logo["width"]}" height="{logo["height"]}"') if logo \
else (shield_url(rec), "")
loading = "" if eager else ' loading="lazy"'
@@ -291,7 +303,7 @@ def plate(rec, *, size="", link=False, eager=False, alt=None):
if url:
if alt is None:
alt = f"{rec['name']} logo" if size else ""
img = logo_img(rec, alt, eager)
img = logo_img(rec, alt, eager, listed=not size)
if link:
label = "" if alt else f'<span class="vh">Full-size logo: {name(rec)}</span>'
img = f'<a href="{esc(url)}">{img}{label}</a>'
+2 -2
View File
@@ -735,11 +735,11 @@ def browse_view(listing, map_html, *, about="", about_title="", about_id="about-
if has_map:
grid = f"""<div class="browse">
<div class="browse__map" id="map">{map_html}</div>
<div class="browse__list">{listing}</div>
<div class="browse__list" id="browse-list">{listing}</div>
</div>"""
else:
grid = f"""<div class="browse browse--no-map">
<div class="browse__list">{listing}{map_html}</div>
<div class="browse__list" id="browse-list">{listing}{map_html}</div>
</div>"""
if about:
grid += about_section(about, about_title or "About these trails", about_id)
+14 -1
View File
@@ -200,6 +200,19 @@ def structured_data(jsonld, body, path, site, noindex=False):
return str(_ld_json_block(obj))
def skip_links(body):
"""More skip links, for a page with a map before a long list of rows: past the map to the
filters and the list, and on to the rows themselves. Each shows only while it has keyboard focus
(style.css .skip-link) and is left out of a page without its target."""
body = str(body)
out = ""
if 'id="browse-list"' in body and 'class="browse__map"' in body:
out += '<a class="skip-link" href="#browse-list">Skip the map</a>'
if 'id="entries"' in body:
out += '<a class="skip-link" href="#entries">Skip to the list of trails</a>'
return out
def layout(title, body, *, path, description="", maps=False, outdoor=False, scripts=(), data=None, site=None,
jsonld=None, og_type="website", noindex=False, image="", image_alt="", alternates=()):
"""Return a complete HTML document.
@@ -311,7 +324,7 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
{chr(10).join(head)}
</head>
<body>
<a class="skip-link" href="#main">Skip to content</a>
<a class="skip-link" href="#main">Skip to content</a>{skip_links(body)}
{header(path, site)}
<main id="main">
{body}
+1 -1
View File
@@ -11,7 +11,7 @@ writes:
/index.html home: overview map and the trail finder with every record
/trails/<id>/index.html one page per record
/trails/<id>/trail.toml the raw record; release.txt beside it where the trail has one
/trails/<id>/shield-thumb.png the list-size copy of a PNG logo (olt/thumbs.py)
/trails/<id>/shield-thumb.png the 256 px copy of a PNG logo; shield-list.png the list-size copy (olt/thumbs.py)
/trails/<id>/card.png the trail's social card, from web/cards/ (olt/cards.py)
/regions/, /regions/<slug>/ Places: the hub and one page per state or province
/lists/, /lists/<key>/ the lists shown today (olt/browse.py); /routes/ is the Routes list
+67
View File
@@ -0,0 +1,67 @@
"""Redirects from the addresses a hiker would guess to a trail's real page.
A trail's page lives at /trails/<id>/, and about half the ids are shorter than the trail's
name (/trails/pacific-crest/), so /trails/pacific-crest-trail/ is a 404 without one of these.
trail_redirects() gives, for each record, the slug of its full name, of its common name, and of
the name plus "Trail" for a trail whose names do not say "trail", wherever that slug is not a
page of its own and only one record could mean it. The canonical address never changes.
"""
import os
import re
TRAILS = "/trails/"
MARKER = "# Guessable trail addresses (olt/redirects.py), one line each, from the records' names.\n"
def slug(text):
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
def candidates(rec):
"""The slugs a hiker might type for a record, in order, without its own id."""
names = [rec["name"], rec.get("common_name") or ""]
found = [slug(n) for n in names if n]
if rec.get("kind") != "route" and not any("trail" in s.split("-") for s in found):
found.append(slug(rec.get("common_name") or rec["name"]) + "-trail")
seen, out = set(), []
for s in found:
if s and s != rec["id"] and s not in seen:
seen.add(s)
out.append(s)
return out
def trail_redirects(recs, taken=()):
"""[(slug, id)] sorted by slug: each a slug that no page has (not an id, not in taken, the
names of other entries under /trails/) and that exactly one record's names give."""
real = {r["id"] for r in recs} | set(taken)
owners = {}
for r in recs:
for s in candidates(r):
owners.setdefault(s, set()).add(r["id"])
return sorted((s, next(iter(ids))) for s, ids in owners.items() if s not in real and len(ids) == 1)
def lines(pairs):
out = []
for s, tid in pairs:
out.append(f"{TRAILS}{s}/ {TRAILS}{tid}/ 301\n")
out.append(f"{TRAILS}{s} {TRAILS}{tid}/ 301\n")
return out
def append_to(out_dir, recs):
"""Add the lines to the publish directory's _redirects (written there from web/static)."""
trails_dir = os.path.join(out_dir, "trails")
taken = os.listdir(trails_dir) if os.path.isdir(trails_dir) else []
pairs = trail_redirects(recs, taken)
path = os.path.join(out_dir, "_redirects")
text = ""
if os.path.isfile(path):
with open(path, encoding="utf-8") as f:
text = f.read()
if text and not text.endswith("\n"):
text += "\n"
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(text + "\n" + MARKER + "".join(lines(pairs)))
return pairs
+19 -3
View File
@@ -1,5 +1,9 @@
"""PNG logo thumbnails for the list and trail pages.
Two sizes: web/thumbs/<id>.png (up to 256 px) for the trail page header and the Logos
page, and web/thumbs-list/<id>.png (up to 200 x 124 px, twice the largest box a list
draws a logo in) for the lists; a logo with no list thumbnail uses the first.
web/thumbs/<id>.png is made by web/tools/make_thumbs.py and committed, from a
PNG logo or (where the logo is a vector) an SVG one. The pages step copies it to
trails/<id>/shield-thumb.png, and the pages show that copy at its real pixel size
@@ -16,7 +20,9 @@ import sys
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
THUMB_DIR = os.path.join(WEB_DIR, "thumbs")
LIST_THUMB_DIR = os.path.join(WEB_DIR, "thumbs-list") # web/thumbs-list/<id>.png: for the lists, twice the size they are shown at
THUMB_NAME = "shield-thumb.png"
LIST_THUMB_NAME = "shield-list.png"
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
THUMB_MAX = 256 # the longest side of a thumbnail, as make_thumbs.py draws it
@@ -57,7 +63,7 @@ def svg_size(path):
return max(1, round(w * scale)), max(1, round(h * scale))
def prepare(rec, out_dir, repo_root, thumb_dir=THUMB_DIR):
def prepare(rec, out_dir, repo_root, thumb_dir=THUMB_DIR, list_thumb_dir=LIST_THUMB_DIR):
"""Copy the record's PNG thumbnail into its output directory and set
rec["derived"]["logo_img"] = {"src", "width", "height"}, the image the pages
show. Without a logo the key is absent and any old copy is removed.
@@ -66,11 +72,21 @@ def prepare(rec, out_dir, repo_root, thumb_dir=THUMB_DIR):
tdir = os.path.join(out_dir, "trails", tid)
dest = os.path.join(tdir, THUMB_NAME)
rec["derived"].pop("logo_img", None)
rec["derived"].pop("list_img", None)
list_dest = os.path.join(tdir, LIST_THUMB_NAME)
shield = rec["derived"]["files"].get("shield", "")
if not shield.endswith((".png", ".svg")):
if os.path.isfile(dest):
os.remove(dest)
for stale in (dest, list_dest):
if os.path.isfile(stale):
os.remove(stale)
return
list_thumb = os.path.join(list_thumb_dir, f"{tid}.png")
if os.path.isfile(list_thumb):
shutil.copyfile(list_thumb, list_dest)
w, h = png_size(list_dest)
rec["derived"]["list_img"] = {"src": f"/trails/{tid}/{LIST_THUMB_NAME}", "width": w, "height": h}
elif os.path.isfile(list_dest):
os.remove(list_dest)
thumb = os.path.join(thumb_dir, f"{tid}.png")
if os.path.isfile(thumb):
shutil.copyfile(thumb, dest)
+14 -8
View File
@@ -1635,26 +1635,32 @@ def places_short(rec):
def description(rec):
"""The meta description, from the record's own fields and at most DESCRIPTION_LIMIT
characters: what it is, how long, where, the usual time where a source states one,
then the first sentence of the summary (or the designation where there is none)."""
then the first sentence of the summary (or the designation where there is none).
Always whole sentences, whatever fits of those."""
mi = words.fmt_int(rec["derived"]["length_mi"])
km = words.fmt_km(rec["length_km"])
built = ""
if rec.get("built_km"):
built = f", {words.fmt_int(words.km_to_mi(rec['built_km']))} miles built,"
text = f"A {kind_word(rec)} of {mi} miles ({km} km){built} {places_short(rec)}"
lead = f"A {kind_word(rec)} of {mi} miles ({km} km){built} {places_short(rec)}"
days = hike.days(rec)
if days:
text += f", usually {days}"
text += "."
tail = hike.one_line(rec)
if not tail and rec.get("designation"):
tail = rec["designation"].strip()
tail = tail[:1].upper() + tail[1:]
if not tail.endswith("."):
tail += "."
if tail:
text += " " + tail
return common.cut_at_word(re.sub(r"\s+", " ", text.replace("`", "")), common.DESCRIPTION_LIMIT)
# Whole sentences, the richest that fits first: the facts with the usual time and the summary's
# first sentence, then without the time, then the facts alone; only a first sentence that is
# itself too long is cut, at a word and with no ellipsis (common.cut_clean).
sentences = [lead + (f", usually {days}" if days else "") + "."]
if days:
sentences.append(lead + ".")
options = [f"{o} {tail}" for o in sentences] if tail else []
options += sentences
options = [re.sub(r"\s+", " ", o.replace("`", "")) for o in options]
return next((o for o in options if len(o) <= common.DESCRIPTION_LIMIT),
common.cut_clean(options[-1], common.DESCRIPTION_LIMIT))
# Ways onward ------------------------------------------------------------------