diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000..6920701 --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,15 @@ +# Citation metadata (https://citation-file-format.github.io/). Every fact here is +# stated in README.md; no author, version or identifier is given because the +# README names none. +cff-version: 1.2.0 +message: "If you use this dataset, please cite it as below." +type: dataset +title: "Long Hikes" +abstract: "A public dataset of long-distance hiking trails in the United States and Canada: one directory per trail, with a written record, the trail's track where it may be shared, and the trail's logo where one exists." +authors: + - name: "Long Hikes" +repository-code: "https://github.com/swaits/longhikes" +url: "https://longhikes.org" +# The records, documents and compiled index are CC0-1.0 (see LICENSE). Tracks keep +# their sources' terms, and trail logos are not covered; see README.md, Licences. +license: CC0-1.0 diff --git a/web/assets/app.js b/web/assets/app.js index 72b22b3..402d1af 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -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 }; }); } diff --git a/web/assets/style.css b/web/assets/style.css index 30ef86e..08851f0 100644 --- a/web/assets/style.css +++ b/web/assets/style.css @@ -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; } +} diff --git a/web/build.py b/web/build.py index 5743790..b8262e8 100644 --- a/web/build.py +++ b/web/build.py @@ -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: diff --git a/web/olt/common.py b/web/olt/common.py index 31526e7..d4e0d4f 100644 --- a/web/olt/common.py +++ b/web/olt/common.py @@ -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'Track policy: {esc(lab)}') -def logo_img(rec, alt, eager=False): - """The logo : 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 : 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'Full-size logo: {name(rec)}' img = f'{img}{label}' diff --git a/web/olt/home.py b/web/olt/home.py index 39360ed..f99017a 100644 --- a/web/olt/home.py +++ b/web/olt/home.py @@ -735,11 +735,11 @@ def browse_view(listing, map_html, *, about="", about_title="", about_id="about- if has_map: grid = f"""
{map_html}
-
{listing}
+
{listing}
""" else: grid = f"""
-
{listing}{map_html}
+
{listing}{map_html}
""" if about: grid += about_section(about, about_title or "About these trails", about_id) diff --git a/web/olt/layout.py b/web/olt/layout.py index ae24544..8371816 100644 --- a/web/olt/layout.py +++ b/web/olt/layout.py @@ -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 += '' + if 'id="entries"' in body: + out += '' + 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)} - +{skip_links(body)} {header(path, site)}
{body} diff --git a/web/olt/pages.py b/web/olt/pages.py index 6522509..0b5c2b9 100644 --- a/web/olt/pages.py +++ b/web/olt/pages.py @@ -11,7 +11,7 @@ writes: /index.html home: overview map and the trail finder with every record /trails//index.html one page per record /trails//trail.toml the raw record; release.txt beside it where the trail has one - /trails//shield-thumb.png the list-size copy of a PNG logo (olt/thumbs.py) + /trails//shield-thumb.png the 256 px copy of a PNG logo; shield-list.png the list-size copy (olt/thumbs.py) /trails//card.png the trail's social card, from web/cards/ (olt/cards.py) /regions/, /regions// Places: the hub and one page per state or province /lists/, /lists// the lists shown today (olt/browse.py); /routes/ is the Routes list diff --git a/web/olt/redirects.py b/web/olt/redirects.py new file mode 100644 index 0000000..5236f93 --- /dev/null +++ b/web/olt/redirects.py @@ -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//, 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 diff --git a/web/olt/thumbs.py b/web/olt/thumbs.py index 5c247c3..fea997b 100644 --- a/web/olt/thumbs.py +++ b/web/olt/thumbs.py @@ -1,5 +1,9 @@ """PNG logo thumbnails for the list and trail pages. +Two sizes: web/thumbs/.png (up to 256 px) for the trail page header and the Logos +page, and web/thumbs-list/.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/.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//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/.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) diff --git a/web/olt/trail.py b/web/olt/trail.py index 76abb9a..a839b9b 100644 --- a/web/olt/trail.py +++ b/web/olt/trail.py @@ -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 ------------------------------------------------------------------ diff --git a/web/static/_headers b/web/static/_headers index af0b2df..0b869f5 100644 --- a/web/static/_headers +++ b/web/static/_headers @@ -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 diff --git a/web/tests/test_images.py b/web/tests/test_images.py index 9711186..e91a30b 100644 --- a/web/tests/test_images.py +++ b/web/tests/test_images.py @@ -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: diff --git a/web/tests/test_quick_wins.py b/web/tests/test_quick_wins.py new file mode 100644 index 0000000..91fecc3 --- /dev/null +++ b/web/tests/test_quick_wins.py @@ -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'Skip to content', doc) + self.assertIn('', doc) + self.assertIn('', 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'.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