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

+83 -31
View File
@@ -1312,38 +1312,90 @@
popup.on('close', function () { shown = null; });
entry.closePopupUnless = function (set) { if (shown && !set[shown.id]) popup.remove(); };
document.addEventListener('olt:units', function () { if (shown) shown.meta.textContent = shown.text(); });
defs.filter(function (d) { return d.hit; }).forEach(function (def) {
map.on('mousemove', def.id, function (e) {
map.getCanvas().style.cursor = 'pointer';
highlight(e.features[0].properties.id);
});
map.on('mouseleave', def.id, function () {
map.getCanvas().style.cursor = '';
highlight('');
});
map.on('click', def.id, function (e) {
var p = e.features[0].properties;
var box = document.createElement('div');
var a = document.createElement('a');
a.href = '/trails/' + encodeURIComponent(p.id) + '/';
a.textContent = p.name;
var meta = document.createElement('p');
var text = function () { return lengthText(Number(p.length_km)) + (p.kind === 'route' ? ' · Route' : ''); };
meta.textContent = text();
box.appendChild(a);
box.appendChild(meta);
if (p.sketch) {
var g = e.features[0].geometry || {};
var pointOnly = (g.type === 'MultiPoint' && g.coordinates.length === 1) || g.type === 'Point';
var note = document.createElement('p');
note.textContent = pointOnly
? 'No GPX here. The ring only marks where it starts and ends; it is not the trail\u2019s path.'
: 'No GPX here. The dotted line only joins the start and the end; it is not the trail\u2019s path.';
box.appendChild(note);
}
popup.setLngLat(e.lngLat).setDOMContent(box).addTo(map);
shown = { id: p.id, meta: meta, text: text };
var hitIds = defs.filter(function (d) { return d.hit; }).map(function (d) { return d.id; });
/* Squared distance, in pixels, from the point (px, py) to the segment a-b. */
function segDist2(px, py, a, b) {
var dx = b.x - a.x, dy = b.y - a.y;
var len2 = dx * dx + dy * dy;
var t = len2 ? Math.max(0, Math.min(1, ((px - a.x) * dx + (py - a.y) * dy) / len2)) : 0;
var cx = a.x + t * dx - px, cy = a.y + t * dy - py;
return cx * cx + cy * cy;
}
function partDist2(px, py, coords, isLine) {
var pts = coords.map(function (c) { return map.project(c); });
if (!isLine || pts.length < 2) {
return pts.reduce(function (m, q) { return Math.min(m, (q.x - px) * (q.x - px) + (q.y - py) * (q.y - py)); }, Infinity);
}
var best = Infinity;
for (var i = 1; i < pts.length; i++) best = Math.min(best, segDist2(px, py, pts[i - 1], pts[i]));
return best;
}
/* Squared pixel distance from the pointer to a feature's geometry. */
function featureDist2(px, py, g) {
if (!g) return Infinity;
if (g.type === 'Point') return partDist2(px, py, [g.coordinates], false);
if (g.type === 'MultiPoint') return partDist2(px, py, g.coordinates, false);
if (g.type === 'LineString') return partDist2(px, py, g.coordinates, true);
if (g.type === 'MultiLineString') {
return g.coordinates.reduce(function (m, part) { return Math.min(m, partDist2(px, py, part, true)); }, Infinity);
}
return Infinity;
}
/* The tracks and markers within a few pixels of the pointer (a few more for a finger than for a
mouse; a track is only about 1.6 px wide), and the nearest one: so that a click or tap close
to a track opens that trail, not only a click exactly on the line. */
function nearestFeature(e) {
var coarse = (e.originalEvent && (e.originalEvent.pointerType === 'touch' || e.originalEvent.type === 'touchend')) ||
(window.matchMedia && matchMedia('(pointer: coarse)').matches);
var pad = coarse ? 14 : 6;
var layers = hitIds.filter(function (id) { return map.getLayer(id); });
if (!layers.length) return null;
var x = e.point.x, y = e.point.y;
var found = map.queryRenderedFeatures([[x - pad, y - pad], [x + pad, y + pad]], { layers: layers });
var best = null, bestD = Infinity;
found.forEach(function (f) {
var d = featureDist2(x, y, f.geometry);
if (d < bestD) { best = f; bestD = d; }
});
return best && bestD <= pad * pad ? best : null;
}
var overId = '';
map.on('mousemove', function (e) {
var f = nearestFeature(e);
var id = f ? f.properties.id : '';
map.getCanvas().style.cursor = f ? 'pointer' : '';
if (id !== overId) { overId = id; highlight(id); }
});
map.on('mouseout', function () {
map.getCanvas().style.cursor = '';
if (overId) { overId = ''; highlight(''); }
});
map.on('click', function (e) {
var hit = nearestFeature(e);
if (!hit) return;
e.features = [hit];
var p = e.features[0].properties;
var box = document.createElement('div');
var a = document.createElement('a');
a.href = '/trails/' + encodeURIComponent(p.id) + '/';
a.textContent = p.name;
var meta = document.createElement('p');
var text = function () { return lengthText(Number(p.length_km)) + (p.kind === 'route' ? ' · Route' : ''); };
meta.textContent = text();
box.appendChild(a);
box.appendChild(meta);
if (p.sketch) {
var g = e.features[0].geometry || {};
var pointOnly = (g.type === 'MultiPoint' && g.coordinates.length === 1) || g.type === 'Point';
var note = document.createElement('p');
note.textContent = pointOnly
? 'No GPX here. The ring only marks where it starts and ends; it is not the trail\u2019s path.'
: 'No GPX here. The dotted line only joins the start and the end; it is not the trail\u2019s path.';
box.appendChild(note);
}
popup.setLngLat(e.lngLat).setDOMContent(box).addTo(map);
shown = { id: p.id, meta: meta, text: text };
});
}
+25
View File
@@ -2521,3 +2521,28 @@ html:not(.js) .saved-body { display: none; }
.numbers > section > h2 { margin-block-end: var(--space-3); font-size: var(--step-2); }
.numbers > section > ul { padding-inline-start: 1.2em; }
.left-out > section { margin-block-start: var(--space-7); }
/* 15. Print ------------------------------------------------------------------ */
/* A trail page printed: the title, facts, summary, sources, the page's drawing of the track and the
elevation profile, in black on white. The navigation, the finder's filters, the buttons, the live
map and its controls are left off, and an outside link shows where it goes. Every rule is inside
@media print, so nothing on a screen changes. */
@media print {
:root { color-scheme: light; }
@page { margin: 1.6cm; }
html, body { background: #fff; color: #000; }
body { font-size: 11pt; }
.skip-link, .site-header, .breadcrumb, .site-footer__base,
.filters, .button, button, .js-only, .save, .glance__toggle,
.map__canvas, .map__status, .map__termini, .maplibregl-ctrl, .maplibregl-popup, .basemap-switch,
.onward, .morelinks { display: none !important; }
/* The live map is a canvas that does not print; the page's own drawing of the track does. */
.map[data-state="ready"] .map__fallback { visibility: visible; transition: none; }
.map { background: #fff; }
main a { color: #000; text-decoration: underline; }
main a[href^="http"]::after { content: " (" attr(href) ")"; font-size: 0.85em; overflow-wrap: anywhere; }
main a[href^="http"]:has(img)::after, main a[href^="http"].vh::after { content: none; }
figure, .block, .panel, .entry, tr { break-inside: avoid; }
h1, h2, h3 { break-after: avoid; }
}
+3 -1
View File
@@ -19,7 +19,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE)
from olt import fingerprint, geo, hike, records # noqa: E402
from olt import fingerprint, geo, hike, records, redirects # noqa: E402
GPX_TOL_M = 5.0
MAP_TOL_M = 30.0
@@ -516,6 +516,8 @@ def main(argv=None):
build_archive(name, recs, out_dir, stats)
copy_static(STATIC_DIR, out_dir, stats)
# The guessable trail addresses (/trails/pacific-crest-trail/) follow the fixed ones in _redirects.
redirects.append_to(out_dir, recs)
pages = import_pages()
if pages is None:
+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 ------------------------------------------------------------------
+11 -1
View File
@@ -31,17 +31,25 @@
# Site data. Matched by file type, not /data/*, so the pages under /data/
# (/data/, /data/schema/, /data/changelog/) revalidate like every other page.
# overview.geojson and trails.json are fetched by page scripts; index.geojson,
# trails.csv and the two archives are downloads.
# trails.csv and the two archives are downloads. These public data files, and the
# trail downloads below (GPX and GeoJSON), also allow cross-origin GET
# (Access-Control-Allow-Origin: *), so that a browser app on another site can fetch
# them. No HTML page and no other file carries it; the security headers above are
# unchanged.
/data/*.json
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=300, must-revalidate
/data/*.geojson
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=300, must-revalidate
/data/*.csv
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=300, must-revalidate
/data/*.zip
Access-Control-Allow-Origin: *
Content-Type: application/zip
Content-Disposition: attachment
Cache-Control: public, max-age=300, must-revalidate
@@ -88,12 +96,14 @@
# Trail downloads: correct media types and a download disposition.
/trails/*/*.gpx
Access-Control-Allow-Origin: *
Content-Type: application/gpx+xml
Content-Disposition: attachment
Cache-Control: public, max-age=3600
X-Robots-Tag: noindex
/trails/*/*.geojson
Access-Control-Allow-Origin: *
Content-Type: application/geo+json
Content-Disposition: attachment
Cache-Control: public, max-age=3600
+1 -1
View File
@@ -100,7 +100,7 @@ class BuiltSiteTest(unittest.TestCase):
def test_the_first_rows_of_a_list_are_eager_and_the_rest_are_lazy(self):
for rel in ("index.html", os.path.join("lists", "under-100-miles", "index.html")):
logos = [i for i in page_imgs(os.path.join(OUT, rel))
if i["_row"] and i.get("src", "").endswith(thumbs.THUMB_NAME)]
if i["_row"] and i.get("src", "").endswith((thumbs.THUMB_NAME, thumbs.LIST_THUMB_NAME))]
self.assertGreater(len(logos), home.EAGER_ROWS + 2, rel)
for img in logos:
if img["_row"] <= home.EAGER_ROWS:
+286
View File
@@ -0,0 +1,286 @@
"""Small site-wide improvements that change nothing on screen: map click tolerance, cross-origin data
files, description endings, guessable-address redirects, the print rules, the extra skip links and the
list-size logo thumbnails."""
import os
import re
import subprocess
import sys
import unittest
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
import serve # noqa: E402
from olt import common, records, redirects, thumbs # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
def setUpModule():
if not os.path.isfile(os.path.join(OUT, "_redirects")):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
def read(relpath):
with open(os.path.join(OUT, *relpath.split("/")), encoding="utf-8") as f:
return f.read()
def asset(name):
with open(os.path.join(WEB, "assets", name), encoding="utf-8") as f:
return f.read()
class MapClickToleranceTest(unittest.TestCase):
"""The click handler itself needs a browser; these check the logic it is built on is in place."""
@classmethod
def setUpClass(cls):
js = asset("app.js")
cls.src = js[js.index("function wireOverview"):js.index("function fitToVisible")]
def test_clicks_and_hovers_look_in_a_box_round_the_pointer_not_at_one_pixel(self):
self.assertIn("queryRenderedFeatures([[x - pad, y - pad], [x + pad, y + pad]]", self.src)
self.assertNotIn("map.on('click', def.id", self.src)
self.assertNotIn("map.on('mousemove', def.id", self.src)
self.assertIn("map.on('click', function (e)", self.src)
def test_a_finger_gets_a_wider_box_than_a_mouse(self):
match = re.search(r"var pad = coarse \? (\d+) : (\d+);", self.src)
self.assertTrue(match)
self.assertGreater(int(match.group(1)), int(match.group(2)))
self.assertGreaterEqual(int(match.group(2)), 4)
def test_the_nearest_feature_wins_and_a_miss_does_nothing(self):
self.assertIn("d < bestD", self.src)
self.assertIn("bestD <= pad * pad", self.src)
self.assertIn("if (!hit) return;", self.src)
def test_the_tracks_are_drawn_as_before(self):
js = asset("app.js")
self.assertIn("{ id: 'olt-line', color: '--trail', width: [3, 1.6, 9, 4]", js)
self.assertNotIn("olt-hit", js) # no extra hit layer: nothing new is drawn
class CrossOriginDataTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.rules = serve.parse_headers(os.path.join(OUT, "_headers"))
def headers(self, path):
out = {}
for pattern, headers in self.rules:
if pattern.match(path):
for name, value in headers:
self.assertNotIn(name.lower(), out, f"{path}: {name} set by two rules")
out[name.lower()] = value
return out
def test_the_public_data_files_allow_any_site_to_fetch_them(self):
for path in ("/data/trails.json", "/data/overview.geojson", "/data/index.geojson", "/data/trails.csv",
"/data/all-gpx.zip", "/trails/appalachian/appalachian.gpx",
"/trails/appalachian/appalachian.geojson"):
self.assertEqual(self.headers(path).get("access-control-allow-origin"), "*", path)
def test_no_page_and_no_other_file_carries_it(self):
for path in ("/", "/index.html", "/data/", "/data/schema/", "/data/changelog/", "/trails/appalachian/",
"/trails/appalachian/index.html", "/404.html", "/feed.xml", "/llms.txt",
"/trails/appalachian/trail.toml", "/trails/appalachian/release.txt", "/assets/og.png"):
self.assertNotIn("access-control-allow-origin", self.headers(path), path)
def test_every_built_data_file_and_trail_download_is_covered(self):
for base, _, names in os.walk(os.path.join(OUT, "data")):
for n in names:
if n.endswith((".json", ".geojson", ".csv", ".zip")):
path = "/" + os.path.relpath(os.path.join(base, n), OUT).replace(os.sep, "/")
self.assertEqual(self.headers(path).get("access-control-allow-origin"), "*", path)
def test_the_security_headers_are_still_on_everything(self):
for path in ("/", "/trails/appalachian/", "/data/trails.json", "/trails/appalachian/appalachian.gpx"):
h = self.headers(path)
self.assertEqual(h.get("x-content-type-options"), "nosniff", path)
self.assertEqual(h.get("referrer-policy"), "strict-origin-when-cross-origin", path)
self.assertIn("frame-ancestors 'none'", h.get("content-security-policy", ""), path)
class DescriptionEndingTest(unittest.TestCase):
def test_cut_clean_ends_at_a_word_with_a_full_stop_and_no_ellipsis(self):
text = "The walk goes " + "on and on and on " * 20 + "to the end."
cut = common.cut_clean(text, 100)
self.assertLessEqual(len(cut), 100)
self.assertTrue(cut.endswith("."))
self.assertNotIn("…", cut)
self.assertEqual(common.cut_clean("Short.", 100), "Short.")
def test_cut_clean_never_ends_on_a_joining_word(self):
cut = common.cut_clean("A long trail through the mountains and valleys of the northern part of the state", 52)
self.assertNotRegex(cut, r"\b(and|of|the|through)\.$")
def test_the_share_description_is_a_whole_sentence_where_one_fits(self):
text = ("A trail of 70 miles (113 km) in Maine, usually 5 days. "
"It follows the ridge and crosses several summits before it drops to the lake shore and the road.")
self.assertEqual(common.share_description(text), "A trail of 70 miles (113 km) in Maine, usually 5 days.")
def test_the_share_description_from_one_long_sentence_ends_at_a_word(self):
got = common.share_description("A trail of " + "many long miles and more " * 12 + "end.")
self.assertLessEqual(len(got), common.SHARE_DESCRIPTION_LIMIT)
self.assertTrue(got.endswith("."))
self.assertNotIn("…", got)
def test_every_built_trail_page_describes_itself_in_whole_sentences(self):
trails = os.path.join(OUT, "trails")
pages = 0
for tid in sorted(os.listdir(trails)):
path = os.path.join(trails, tid, "index.html")
if not os.path.isfile(path):
continue
doc = read(f"trails/{tid}/index.html")
desc = re.search(r'<meta name="description" content="([^"]*)"', doc).group(1)
og = re.search(r'<meta property="og:description" content="([^"]*)"', doc).group(1)
tw = re.search(r'<meta name="twitter:description" content="([^"]*)"', doc).group(1)
pages += 1
for text in (desc, og, tw):
self.assertNotIn("…", text, tid)
self.assertTrue(text.endswith("."), f"{tid}: {text}")
self.assertEqual(og, tw, tid)
self.assertTrue(desc.startswith(og), tid) # the share text is cut from the same text
self.assertGreater(pages, 200)
class GuessableAddressTest(unittest.TestCase):
@staticmethod
def rec(tid, name, common_name="", kind="trail"):
r = {"id": tid, "name": name, "kind": kind}
if common_name:
r["common_name"] = common_name
return r
def test_the_full_name_the_common_name_and_the_name_plus_trail_redirect(self):
recs = [self.rec("pacific-crest", "Pacific Crest National Scenic Trail", "Pacific Crest Trail"),
self.rec("wonderland", "Wonderland"),
self.rec("high-line", "High Line Route", kind="route")]
got = dict(redirects.trail_redirects(recs))
self.assertEqual(got["pacific-crest-trail"], "pacific-crest")
self.assertEqual(got["pacific-crest-national-scenic-trail"], "pacific-crest")
self.assertEqual(got["wonderland-trail"], "wonderland")
self.assertEqual(got["high-line-route"], "high-line")
self.assertNotIn("high-line-route-trail", got)
def test_a_real_page_is_never_shadowed_and_an_ambiguous_slug_is_dropped(self):
recs = [self.rec("avon-trail", "Avon Trail"), self.rec("avon", "Avon"),
self.rec("a", "Same Name Trail"), self.rec("b", "Same Name Trail")]
got = dict(redirects.trail_redirects(recs, taken=["taken-trail"]))
self.assertNotIn("avon-trail", got) # the real page of the first record
self.assertNotIn("same-name-trail", got) # two records give it
self.assertEqual(redirects.trail_redirects([self.rec("x", "Taken Trail")], taken=["taken-trail"]), [])
def test_the_built_redirects_shadow_no_page_and_none_is_ambiguous(self):
recs = records.load_records(ROOT)
ids = {r["id"] for r in recs}
text = read("_redirects")
rules = [line.split() for line in text.splitlines() if line.strip() and not line.startswith("#")]
sources = [r[0] for r in rules]
self.assertEqual(len(sources), len(set(sources)), "a source is listed twice")
trail_rules = [r for r in rules if r[0].startswith("/trails/")]
self.assertGreater(len(trail_rules), 100)
for source, dest, status in trail_rules:
slug = source[len("/trails/"):].strip("/")
self.assertNotIn(slug, ids, f"{source} shadows a trail page")
self.assertFalse(os.path.exists(os.path.join(OUT, "trails", slug)), f"{source} shadows a built path")
self.assertEqual(status, "301")
self.assertRegex(dest, r"^/trails/[^/]+/$")
self.assertIn(dest.split("/")[2], ids, dest)
self.assertTrue(os.path.isfile(os.path.join(OUT, *dest.strip("/").split("/"), "index.html")), dest)
# the one address a hiker types for a trail named differently from its id
self.assertIn(["/trails/pacific-crest-trail/", "/trails/pacific-crest/", "301"], rules)
# one destination per slug: no slug is given by two records
by_slug = {}
for source, dest, _ in trail_rules:
by_slug.setdefault(source.rstrip("/"), set()).add(dest)
self.assertTrue(all(len(d) == 1 for d in by_slug.values()))
for old in ("/lists/under-100-km/", "/lists/under-100-km"): # the fixed ones are kept
self.assertIn(old, sources)
class PrintRulesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.css = asset("style.css")
cls.start = cls.css.index("@media print {")
cls.block = cls.css[cls.start:]
def test_the_print_rules_are_one_block_at_the_end_and_nothing_follows_it(self):
self.assertEqual(self.css.count("@media print {"), 1)
self.assertEqual(self.block.count("{"), self.block.count("}"))
depth, closed_at = 0, None
for i, ch in enumerate(self.block):
depth += (ch == "{") - (ch == "}")
if depth == 0 and ch == "}":
closed_at = i
break
self.assertEqual(self.block[closed_at + 1:].strip(), "")
def test_the_chrome_is_left_off_and_the_text_is_black_on_white(self):
for needle in (".site-header", ".breadcrumb", ".filters", ".button", ".maplibregl-ctrl", ".map__canvas",
".skip-link", "display: none !important", "background: #fff", "color: #000",
'a[href^="http"]::after', "attr(href)"):
self.assertIn(needle, self.block)
def test_the_title_facts_sources_and_drawings_are_not_hidden(self):
hidden = re.search(r"([^{}]*)\{ display: none !important; \}", self.block).group(1)
for kept in (".titleblock", ".facts", ".trail-text", ".elev", ".map__fallback", ".mapfig", ".block"):
self.assertNotIn(kept + ",", hidden + ",")
self.assertNotIn(kept + " ", hidden + " ")
class SkipLinkTest(unittest.TestCase):
def test_the_home_page_can_skip_the_map_and_go_to_the_list(self):
doc = read("index.html")
self.assertIn('<a class="skip-link" href="#main">Skip to content</a>', doc)
self.assertIn('<a class="skip-link" href="#browse-list">Skip the map</a>', doc)
self.assertIn('<a class="skip-link" href="#entries">Skip to the list of trails</a>', doc)
for target in ("browse-list", "entries"):
self.assertEqual(doc.count(f'id="{target}"'), 1, target)
def test_a_page_without_those_targets_gets_only_the_one_skip_link(self):
doc = read("trails/appalachian/index.html")
self.assertEqual(doc.count('class="skip-link"'), 1)
def test_every_skip_link_has_a_target_on_its_page(self):
for page in ("index.html", "regions/index.html", "trails/appalachian/index.html", "lists/index.html"):
doc = read(page)
for target in re.findall(r'class="skip-link" href="#([^"]+)"', doc):
self.assertEqual(doc.count(f'id="{target}"'), 1, f"{page}: #{target}")
class ListThumbnailTest(unittest.TestCase):
def test_a_list_thumbnail_is_at_most_twice_the_largest_box_a_list_draws(self):
for name in os.listdir(thumbs.LIST_THUMB_DIR):
w, h = thumbs.png_size(os.path.join(thumbs.LIST_THUMB_DIR, name))
self.assertLessEqual(w, 200, name)
self.assertLessEqual(h, 124, name)
self.assertTrue(os.path.isfile(os.path.join(thumbs.THUMB_DIR, name)), f"{name}: no full thumbnail")
def test_the_list_shows_the_small_copy_with_its_own_size_and_the_header_the_larger(self):
home_doc = read("index.html")
m = re.search(r'<img src="(/trails/([^/]+)/shield-list\.png)" alt="" width="(\d+)" height="(\d+)"', home_doc)
self.assertTrue(m)
w, h = thumbs.png_size(os.path.join(OUT, *m.group(1).strip("/").split("/")))
self.assertEqual((int(m.group(3)), int(m.group(4))), (w, h))
page = read(f"trails/{m.group(2)}/index.html")
self.assertIn(f'src="/trails/{m.group(2)}/shield-thumb.png"', page)
self.assertNotIn("shield-list.png", page)
def test_the_small_copies_are_much_smaller_in_all(self):
small = big = 0
for name in os.listdir(thumbs.LIST_THUMB_DIR):
small += os.path.getsize(os.path.join(thumbs.LIST_THUMB_DIR, name))
big += os.path.getsize(os.path.join(thumbs.THUMB_DIR, name))
self.assertLess(small, big * 0.6)
if __name__ == "__main__":
unittest.main()
+22 -7
View File
@@ -113,14 +113,28 @@ class TrailDescriptionTest(unittest.TestCase):
self.assertTrue(text.startswith("A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months."), text)
self.assertIn("A long walk along the crest of the Example Range", text)
def test_at_most_155_characters_cut_at_a_word(self):
def test_at_most_155_characters_in_whole_sentences(self):
rec = at()
rec["hike"]["summary"] = "The walk goes " + "on and on and on " * 20 + "to the end."
text = trail.description(rec)
self.assertLessEqual(len(text), common.DESCRIPTION_LIMIT)
self.assertTrue(text.endswith("…"))
self.assertFalse(text[:-1].endswith(" "))
self.assertTrue(text[:-1].rsplit(" ", 1)[1] in ("on", "and", "goes", "walk", "The"))
self.assertEqual(text, "A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months.")
self.assertNotIn("\u2026", text)
def test_a_first_sentence_too_long_is_cut_at_a_word_with_no_ellipsis(self):
rec = at()
rec["common_name"] = rec["name"] = "N" * 58
rec["regions"] = ["GA", "NC", "TN", "VA", "WV", "MD", "PA", "NJ", "NY", "CT", "MA", "VT", "NH", "ME"]
text = trail.description(rec)
self.assertLessEqual(len(text), common.DESCRIPTION_LIMIT)
self.assertTrue(text.endswith("."))
self.assertNotIn("\u2026", text)
def test_the_summary_sentence_follows_when_it_fits(self):
rec = at()
rec["hike"]["summary"] = "A short walk."
self.assertEqual(trail.description(rec),
"A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months. A short walk.")
def test_no_stock_sentence(self):
for rec in (at(), fake(1), fake(2, hike={})):
@@ -234,13 +248,14 @@ class TitleAndShareTextTest(unittest.TestCase):
"following the crest of the Appalachian Mountains from Georgia to Maine, and more")
got = common.share_description(words)
self.assertLessEqual(len(got), 125)
self.assertTrue(got.endswith("\u2026"))
self.assertTrue(got.endswith("."))
self.assertNotIn("\u2026", got)
self.assertTrue(words.startswith(got[:-1]))
self.assertIsNone(re.search(r"(,|\b(and|or|but|with|to|of|the|in))\u2026$", got), got)
self.assertIsNone(re.search(r"(,|\b(and|or|but|with|to|of|the|in))\.$", got), got)
for limit in range(40, 125):
cut = common.share_description(words, limit)
self.assertLessEqual(len(cut), limit)
self.assertIsNone(re.search(r"([,;:]|\b(and|or|but|with|to|of|the|a|in|by|from))\u2026?$", cut), cut)
self.assertIsNone(re.search(r"([,;:]|\b(and|or|but|with|to|of|the|a|in|by|from))\.?$", cut), cut)
def test_the_search_description_is_unchanged_and_the_share_one_is_cut_from_it(self):
desc = ("A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months. "
+3 -3
View File
@@ -157,17 +157,17 @@ class BuiltPagesTest(unittest.TestCase):
def test_list_pages_show_thumbnails_not_full_size_pngs(self):
for path, img in self.all_imgs:
self.assertFalse(img.get("src", "").endswith("/shield.png"), f"{path} shows {img.get('src')}")
for page in ("index.html", os.path.join("logos", "index.html")):
for page, name in (("index.html", thumbs.LIST_THUMB_NAME), (os.path.join("logos", "index.html"), thumbs.THUMB_NAME)):
with open(os.path.join(OUT, page), encoding="utf-8") as f:
doc = f.read()
for tid in self.png:
self.assertIn(f'src="/trails/{tid}/shield-thumb.png"', doc, f"{page} for {tid}")
self.assertIn(f'src="/trails/{tid}/{name}"', doc, f"{page} for {tid}")
def test_thumbnail_width_and_height_match_the_file(self):
seen = 0
for path, img in self.all_imgs:
src = img.get("src", "")
if not src.endswith("/" + thumbs.THUMB_NAME):
if not src.endswith(("/" + thumbs.THUMB_NAME, "/" + thumbs.LIST_THUMB_NAME)):
continue
seen += 1
w, h = thumbs.png_size(os.path.join(OUT, src.lstrip("/")))
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

+27 -19
View File
@@ -11,6 +11,11 @@ the site build itself is standard library only and does not run this.
python3 web/tools/make_thumbs.py [--force]
It also writes web/thumbs-list/<id>.png, the same logo fitted within LIST_W x LIST_H
(twice the largest box the lists draw a logo in, 7 rem plate less its padding and
border: about 99 x 62 CSS px), for the lists, so a list does not download 256 px
images to show them at a third of that. The trail page header and the Logos page
keep the 256 px thumbnail.
A thumbnail newer than its source is left alone unless --force is given.
Thumbnails whose source no longer exists are removed.
"""
@@ -23,7 +28,9 @@ import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
THUMBS = os.path.join(os.path.dirname(HERE), "thumbs")
LIST_THUMBS = os.path.join(os.path.dirname(HERE), "thumbs-list")
MAX_SIDE = 256
LIST_W, LIST_H = 200, 124 # 2 x (99 x 62 CSS px), for high-density screens
def sources():
@@ -41,14 +48,14 @@ def sources():
return found
def make_thumb(src, dst):
def make_thumb(src, dst, box=(MAX_SIDE, MAX_SIDE)):
"""Write one thumbnail with ImageMagick, then optimise it when optipng is present."""
if src.endswith(".svg"):
# Drawn at 384 dpi (so the drawing is larger than the thumbnail), then fitted.
cmd = ["magick", "-background", "none", "-density", "384", src, "-strip",
"-resize", f"{MAX_SIDE}x{MAX_SIDE}>", "PNG32:" + dst]
"-resize", f"{box[0]}x{box[1]}>", "PNG32:" + dst]
else:
cmd = ["magick", src, "-strip", "-resize", f"{MAX_SIDE}x{MAX_SIDE}>", "PNG32:" + dst]
cmd = ["magick", src, "-strip", "-resize", f"{box[0]}x{box[1]}>", "PNG32:" + dst]
try:
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
@@ -68,26 +75,27 @@ def main(argv=None):
if shutil.which("magick") is None:
sys.exit("make_thumbs: 'magick' (ImageMagick 7) was not found on the PATH; install ImageMagick and retry")
os.makedirs(THUMBS, exist_ok=True)
srcs = sources()
written = skipped = removed = 0
total = 0
for tid, src in srcs.items():
dst = os.path.join(THUMBS, f"{tid}.png")
if not args.force and os.path.isfile(dst) and os.path.getmtime(dst) >= os.path.getmtime(src):
skipped += 1
continue
make_thumb(src, dst)
size = os.path.getsize(dst)
total += size
written += 1
print(f"wrote {os.path.relpath(dst, ROOT)} ({size} bytes)")
for out_dir, box in ((THUMBS, (MAX_SIDE, MAX_SIDE)), (LIST_THUMBS, (LIST_W, LIST_H))):
os.makedirs(out_dir, exist_ok=True)
for tid, src in srcs.items():
dst = os.path.join(out_dir, f"{tid}.png")
if not args.force and os.path.isfile(dst) and os.path.getmtime(dst) >= os.path.getmtime(src):
skipped += 1
continue
make_thumb(src, dst, box)
size = os.path.getsize(dst)
total += size
written += 1
print(f"wrote {os.path.relpath(dst, ROOT)} ({size} bytes)")
for name in sorted(os.listdir(THUMBS)):
if name.endswith(".png") and name[:-4] not in srcs:
os.remove(os.path.join(THUMBS, name))
removed += 1
print(f"removed {os.path.relpath(os.path.join(THUMBS, name), ROOT)} (no source)")
for name in sorted(os.listdir(out_dir)):
if name.endswith(".png") and name[:-4] not in srcs:
os.remove(os.path.join(out_dir, name))
removed += 1
print(f"removed {os.path.relpath(os.path.join(out_dir, name), ROOT)} (no source)")
print(f"total: {written} written ({total} bytes), {skipped} up to date, {removed} removed")
return 0