Add Nearest to me to every list's sort control

Choosing it asks the browser for the visitor's position once and orders the list by straight-line
distance to the nearest point of each trail's track on the overview map (or its start and end,
where it has no track), shown on each row in miles or kilometres. The position stays in the page:
it is not stored, sent or put in the address. Trails with no position go last and are counted;
a refused or failed request puts the list back in its earlier order with a plain line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 14:09:16 -07:00
1 parent 3ff2281129
commit d89a5f0da7
4 files changed
+391 -7

No files matched your search

+226 -5
View File
@@ -1468,6 +1468,87 @@
finder and the other controls below never wait for a map. */
document.querySelectorAll('.mapfig[data-map]').forEach(initMap);
/* near:begin — pure, with no page: web/tests/test_near.py runs this under node.
Distance from a position to each trail, over the geometry the overview map draws
(/data/overview.geojson): for a trail with a track, every point of the track as drawn (simplified
to about 750 m), reached along its lines; for a trail with no track, the points of its sketch
(its start and its end). A trail the file does not hold has no position. */
var Near = (function () {
var EARTH_KM = 6371.0088;
function vec(lon, lat) {
var a = lon * Math.PI / 180, b = lat * Math.PI / 180, c = Math.cos(b);
return [c * Math.cos(a), c * Math.sin(a), Math.sin(b)];
}
function dot(u, v) { return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; }
function cross(u, v) { return [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; }
function len(u) { return Math.sqrt(dot(u, u)); }
function angle(u, v) { return Math.atan2(len(cross(u, v)), dot(u, v)); }
/* The angle (radians) from p to the nearest point of the great-circle arc a to b. */
function toArc(p, a, b) {
var n = cross(a, b), nn = len(n);
if (nn < 1e-12) return angle(p, a);
n = [n[0] / nn, n[1] / nn, n[2] / nn];
var pn = dot(p, n);
var c = [p[0] - pn * n[0], p[1] - pn * n[1], p[2] - pn * n[2]], cn = len(c);
if (cn > 1e-12) {
c = [c[0] / cn, c[1] / cn, c[2] / cn];
if (dot(cross(a, c), n) >= 0 && dot(cross(c, b), n) >= 0) return angle(p, c);
}
return Math.min(angle(p, a), angle(p, b));
}
/* The shapes of a FeatureCollection, by trail id: {points: [vec], lines: [[vec]]}. */
function shapesOf(fc) {
var out = {};
((fc && fc.features) || []).forEach(function (f) {
var p = f.properties || {}, g = f.geometry || {};
if (!p.id) return;
var shape = out[p.id] || (out[p.id] = { points: [], lines: [] });
function line(coords) { return coords.map(function (c) { return vec(c[0], c[1]); }); }
if (p.sketch) {
/* a sketch's dotted line is not the trail; its points are */
if (g.type === 'MultiPoint') g.coordinates.forEach(function (c) { shape.points.push(vec(c[0], c[1])); });
} else if (g.type === 'LineString') shape.lines.push(line(g.coordinates));
else if (g.type === 'MultiLineString') g.coordinates.forEach(function (l) { shape.lines.push(line(l)); });
});
return out;
}
/* Kilometres from a position to the nearest point of one shape, or null for a shape with none. */
function kmTo(shape, lon, lat) {
var p = vec(lon, lat), best = Infinity;
shape.points.forEach(function (v) { best = Math.min(best, angle(p, v)); });
shape.lines.forEach(function (l) {
if (l.length === 1) best = Math.min(best, angle(p, l[0]));
for (var i = 1; i < l.length; i++) best = Math.min(best, toArc(p, l[i - 1], l[i]));
});
return best === Infinity ? null : best * EARTH_KM;
}
/* {id: km} for every shape that has a point. */
function distances(shapes, lon, lat) {
var out = {};
Object.keys(shapes).forEach(function (id) {
var km = kmTo(shapes[id], lon, lat);
if (km !== null) out[id] = km;
});
return out;
}
/* Order two rows ({km: number or null, name}): the nearer first; a row with no position last. */
function compare(a, b) {
if (a.km === null || b.km === null) {
if (a.km === null && b.km === null) return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
return a.km === null ? 1 : -1;
}
return a.km - b.km || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
}
return { kmTo: kmTo, shapesOf: shapesOf, distances: distances, compare: compare };
})();
/* near:end */
/* 2b. Sorting every list of trails -----------------------------------------
The same orders as facets.SORTS in Python, over the rows' data-*
attributes. The "Sort by" select is the one control for keyboard and
@@ -1478,7 +1559,7 @@
on load and on back/forward. */
var SORT_KEYS = { 'name': 1, 'name-desc': 1, 'length-desc': 1, 'length-asc': 1,
'time-asc': 1, 'time-desc': 1, 'climb-desc': 1, 'climb-asc': 1 };
'time-asc': 1, 'time-desc': 1, 'climb-desc': 1, 'climb-asc': 1, 'nearest': 1 };
var SORT_OLD = { 'long': 'length-desc', 'short': 'length-asc', 'quick': 'time-asc', 'climb': 'climb-desc' };
var SORT_COLUMN = { 'here': 'name', 'name': 'name', 'name-desc': 'name', 'length-desc': 'length', 'length-asc': 'length',
'time-asc': 'time', 'time-desc': 'time', 'climb-desc': 'climb', 'climb-asc': 'climb' };
@@ -1510,6 +1591,11 @@
if (a.dataset.match !== b.dataset.match && a.dataset.match !== undefined && b.dataset.match !== undefined) {
return cmpNum(Number(a.dataset.match), Number(b.dataset.match));
}
if (key === 'nearest') {
var ad = a.dataset.away, bd = b.dataset.away;
return Near.compare({ km: ad === '' || ad == null ? null : Number(ad), name: an },
{ km: bd === '' || bd == null ? null : Number(bd), name: bn });
}
if (key === 'saved') {
var ao = a.dataset.order ? Number(a.dataset.order) : Infinity;
var bo = b.dataset.order ? Number(b.dataset.order) : Infinity;
@@ -1569,8 +1655,134 @@
if (status.textContent !== text) status.textContent = text;
}
/* Nearest to me. Choosing it asks the browser for the visitor's position, once a page, and fetches
the overview geometry (the file the maps draw, usually in the cache already). Both stay in
this page: the position is held in a variable, never put in the address, stored or sent.
Each row then carries data-away (km, or '' with no position) and a "From you" figure in its
facts, in the reader's units by CSS. If the position or the geometry is not to be had, the list goes
back to the order it had and a line says so. root.dataset.near: 'wait', 'on' or 'fail'. */
var nearAway = null; /* {id: km}, once known */
var nearLoading = null;
var NEAR_PRIVACY = 'Straight-line distance from where you are. Your position stays in this browser: it is not stored, sent or put in the address.';
function loadNear() {
if (nearLoading) return nearLoading;
var position = new Promise(function (resolve, reject) {
if (!navigator.geolocation) { reject('position'); return; }
navigator.geolocation.getCurrentPosition(function (p) { resolve(p.coords); }, function () { reject('position'); },
{ timeout: 20000, maximumAge: 600000 });
});
var shapes = fetch('/data/overview.geojson', { credentials: 'same-origin' })
.then(function (r) { if (!r.ok) throw new Error(r.status); return r.json(); })
.then(Near.shapesOf)
.catch(function () { throw 'data'; });
nearLoading = Promise.all([position, shapes]).then(function (v) {
nearAway = Near.distances(v[1], v[0].longitude, v[0].latitude);
return nearAway;
}).catch(function (e) { nearLoading = null; throw e; });
return nearLoading;
}
function awayHtml(km) {
function one(v, unit) { return fmt.format(v < 10 ? Math.round(v * 10) / 10 : Math.round(v)) + ' ' + unit; }
return '<span class="len len--inline"><span class="len__mi">' + one(km / KM_PER_MI, 'mi') +
'</span><span class="len__km">' + one(km, 'km') + '</span></span>';
}
function showAway(root, away) {
root.querySelectorAll('.entry[data-id]').forEach(function (li) {
var fact = li.querySelector('.entry__away');
if (!away) {
if (fact) fact.remove();
delete li.dataset.away;
return;
}
var km = away[li.dataset.id];
li.dataset.away = km === undefined ? '' : String(km);
var facts = li.querySelector('.entry__facts');
if (!fact && facts) {
fact = document.createElement('div');
fact.className = 'entry__more entry__away';
fact.innerHTML = '<dt>From you</dt><dd></dd>';
facts.appendChild(fact);
}
if (fact) fact.querySelector('dd').innerHTML = km === undefined ? 'no position on file' : awayHtml(km);
});
}
/* The line under the count while Nearest to me is on (and the plain line when it could not be). The
number of trails with no position is of the rows shown, so it follows the filters. */
function refreshNearNote(root) {
var note = root.querySelector('[data-near-note]');
var mode = root.dataset.near || '';
if (!mode) { if (note) note.hidden = true; return; }
if (!note) {
var head = root.querySelector('.results-head');
if (!head) return;
note = document.createElement('p');
note.className = 'results-note';
note.setAttribute('data-near-note', '');
head.parentNode.insertBefore(note, head.nextSibling);
}
var text = mode === 'wait' ? 'Waiting for your position…' : mode === 'fail' ? (root._nearFail || '') : NEAR_PRIVACY;
if (mode === 'on') {
var none = 0;
root.querySelectorAll('.entry[data-id]').forEach(function (li) { if (!li.hidden && li.dataset.away === '') none += 1; });
if (none) text += ' ' + none + (none === 1 ? ' trail has' : ' trails have') + ' no position on file and ' + (none === 1 ? 'is' : 'are') + ' listed last.';
}
setNodeText(note, text);
note.hidden = !text;
}
function setNodeText(node, text) { if (node.textContent !== text) node.textContent = text; }
function nearFallback(root, why) {
var select = root.querySelector('[data-sort-select]');
var back = root._lastKey || defaultSortOf(root);
root._nearFail = why === 'data' ? 'Distances could not be loaded, so the list is back in its earlier order.'
: 'Your position was not available, so the list is back in its earlier order.';
root.dataset.near = '';
applySortUI(root, back, false);
root.dataset.near = 'fail';
root._failKey = back;
refreshNearNote(root);
var status = root.querySelector('[data-sort-status]');
if (status) status.textContent = root._nearFail;
root.dispatchEvent(new CustomEvent('olt:sortfallback', { detail: { key: back } }));
}
function applyNearest(root, announce) {
var select = root.querySelector('[data-sort-select]');
if (select && select.value !== 'nearest') select.value = 'nearest';
if (nearAway) {
root.dataset.near = 'on';
showAway(root, nearAway);
sortEntriesIn(root, 'nearest');
syncSortHeads(root, 'nearest');
refreshNearNote(root);
if (announce) announceSort(root, 'nearest');
return 'nearest';
}
if (root.dataset.near !== 'wait') {
root.dataset.near = 'wait';
refreshNearNote(root);
loadNear().then(function () {
if (root.dataset.near === 'wait' && (!select || select.value === 'nearest')) applyNearest(root, announce);
}, function (why) {
if (root.dataset.near === 'wait' && (!select || select.value === 'nearest')) nearFallback(root, why);
});
}
return 'nearest';
}
function applySortUI(root, key, announce) {
key = normalizeSortKey(key, defaultSortOf(root));
if (key === 'nearest') return applyNearest(root, announce);
if (root.dataset.near && !(root.dataset.near === 'fail' && key === root._failKey)) {
delete root.dataset.near;
showAway(root, null);
refreshNearNote(root);
}
root._lastKey = key;
sortEntriesIn(root, key);
var select = root.querySelector('[data-sort-select]');
if (select && select.value !== key) select.value = key;
@@ -1591,12 +1803,19 @@
}
function sortFromUrl(root) {
return normalizeSortKey(new URLSearchParams(window.location.search).get('sort'), defaultSortOf(root));
return normalizeSortKey(sortInAddress(), defaultSortOf(root));
}
/* The order the address names. Nearest to me is never in an address: a link is opened by someone
else, who has not chosen to be asked where they are. */
function sortInAddress() {
var key = new URLSearchParams(window.location.search).get('sort');
return key === 'nearest' ? '' : key;
}
function replaceSortInUrl(root, key) {
var p = new URLSearchParams(window.location.search);
if (key === defaultSortOf(root)) p.delete('sort'); else p.set('sort', key);
if (key === defaultSortOf(root) || key === 'nearest') p.delete('sort'); else p.set('sort', key);
var q = p.toString().replace(/%2C/g, ','); /* a Saved list's t=a,b,c stays readable */
window.history.replaceState(null, '', (q ? '?' + q : window.location.pathname) + window.location.hash);
}
@@ -1606,6 +1825,7 @@
if (root.hasAttribute('data-finder')) return; /* the filter bar wires its own list */
var select = root.querySelector('[data-sort-select]');
var current = defaultSortOf(root);
root.addEventListener('olt:sortfallback', function (e) { current = e.detail.key; });
function setSort(key, updateUrl, announce) {
current = applySortUI(root, key, announce);
if (updateUrl) replaceSortInUrl(root, current);
@@ -1987,7 +2207,7 @@
if (s.month) p.set('month', s.month);
if (s.kind) p.set('kind', s.kind);
MULTI.forEach(function (name) { if (s[name].length) p.set(name, s[name].join(',')); });
if (sort && sort.value !== defaultSort) p.set('sort', sort.value);
if (sort && sort.value !== defaultSort && sort.value !== 'nearest') p.set('sort', sort.value);
return p.toString();
}
@@ -2041,7 +2261,7 @@
MULTI.forEach(function (name) {
boxes(name).forEach(function (b) { b.checked = chosen[name].indexOf(b.value) !== -1; });
});
if (sort) sort.value = normalizeSortKey(p.get('sort'), defaultSort);
if (sort) sort.value = normalizeSortKey(p.get('sort') === 'nearest' ? '' : p.get('sort'), defaultSort);
}
function applySort() {
@@ -2185,6 +2405,7 @@
/* Clear is offered only when something is set: a search, or any filter. */
if (clear) clear.hidden = !(s.q || all);
refreshNearNote(resultsRoot);
maps.forEach(function (m) { if (m.kind === 'overview') setVisible(m, shown); });
if (updateUrl) {
var q = toQuery(s);
+5 -1
View File
@@ -489,6 +489,10 @@ SAVED_ORDER = ("saved", "Order saved")
HERE_ORDER = "here"
# The last order of every list: nearest to the visitor. app.js asks the browser for the position when
# it is chosen and keeps it in the page only; it is never in the address, so no list opens in it.
NEAREST = ("nearest", "Nearest to me")
def sort_select(default_sort="name", saved=False, ranked="", wholly=None):
"""The one sort control of every list of trails, with the page's
@@ -510,7 +514,7 @@ def sort_select(default_sort="name", saved=False, ranked="", wholly=None):
default_sort = facets.normalize_sort(default_sort)
options = "".join(
f'\n <option value="{esc(k)}"{" selected" if k == default_sort else ""}>{esc(label)}</option>'
for k, label in sorts)
for k, label in tuple(sorts) + (NEAREST,))
return f"""<label class="results-sort"><span class="results-sort__label">Sort by</span>
<select class="select" id="sort" name="sort" data-sort-select>{options}
</select>
+158
View File
@@ -0,0 +1,158 @@
"""Nearest to me: the distance and the order (app.js, between the near markers, run under node), the
option in every list's sort control, and what the script keeps out of the address.
The position never reaches Python or the page's data; the browser exercise (a granted position)
is not part of the suite.
"""
import json
import math
import os
import shutil
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)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from olt import hike, home # noqa: E402
from olt import records as recordsmod # noqa: E402
NODE = shutil.which("node")
DENVER = (-104.9903, 39.7392) # lon, lat
TORONTO = (-79.3832, 43.6532)
def js():
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
text = f.read()
return text[text.index("/* near:begin"):text.index("/* near:end */")]
def run(expr, data=None):
prog = js() + "\nvar input = JSON.parse(require('fs').readFileSync(0, 'utf8'));\nprocess.stdout.write(JSON.stringify(" + expr + "));"
out = subprocess.run([NODE, "-e", prog], input=json.dumps(data), capture_output=True, text=True, check=True)
return json.loads(out.stdout)
def haversine(a, b):
(lo1, la1), (lo2, la2) = a, b
p1, p2 = math.radians(la1), math.radians(la2)
h = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lo2 - lo1) / 2) ** 2
return 2 * 6371.0088 * math.asin(math.sqrt(h))
def feature(tid, geometry, **props):
return {"type": "Feature", "properties": dict(id=tid, **props), "geometry": geometry}
@unittest.skipUnless(NODE, "node is not installed")
class DistanceTest(unittest.TestCase):
def test_a_point_to_a_point_is_the_great_circle_distance(self):
fc = {"features": [feature("p", {"type": "MultiPoint", "coordinates": [list(TORONTO)]}, sketch=True)]}
got = run("Near.distances(Near.shapesOf(input), %s, %s)" % (DENVER[0], DENVER[1]), fc)["p"]
self.assertAlmostEqual(got, haversine(DENVER, TORONTO), delta=0.5)
self.assertTrue(2000 < got < 2300)
def test_a_line_is_reached_at_its_nearest_point_not_its_nearest_vertex(self):
# a long east-west line along 40 N with its vertices far from the position: the position is 10 km north of its middle
line = feature("l", {"type": "LineString", "coordinates": [[-110, 40], [-100, 40]]})
pos = (-105, 40.09)
got = run("Near.distances(Near.shapesOf(input), %s, %s)" % pos, {"features": [line]})["l"]
# the great circle between the two vertices bows north of 40 N, so the position is within a few km of the line
self.assertLess(got, 12)
vertex = min(haversine(pos, (-110, 40)), haversine(pos, (-100, 40)))
self.assertGreater(vertex, 400)
def test_a_position_beyond_the_end_of_a_line_is_measured_to_the_end(self):
line = feature("l", {"type": "LineString", "coordinates": [[-110, 40], [-109, 40]]})
pos = (-107, 40)
got = run("Near.distances(Near.shapesOf(input), %s, %s)" % pos, {"features": [line]})["l"]
self.assertAlmostEqual(got, haversine(pos, (-109, 40)), delta=0.5)
def test_a_multiline_takes_its_nearest_part(self):
ml = feature("m", {"type": "MultiLineString", "coordinates": [[[-120, 30], [-119, 30]], [[-105, 39.8], [-104.9, 39.8]]]})
got = run("Near.distances(Near.shapesOf(input), %s, %s)" % DENVER, {"features": [ml]})["m"]
self.assertLess(got, 15)
def test_a_sketch_is_its_points_not_its_dotted_line(self):
line = feature("s", {"type": "LineString", "coordinates": [[-110, 40], [-100, 40]]}, sketch=True)
pts = feature("s", {"type": "MultiPoint", "coordinates": [[-110, 40], [-100, 40]]}, sketch=True)
got = run("Near.distances(Near.shapesOf(input), -105, 40.09)", {"features": [line, pts]})["s"]
self.assertGreater(got, 400)
def test_a_trail_the_file_does_not_hold_has_no_distance(self):
got = run("Near.distances(Near.shapesOf(input), -105, 40)", {"features": []})
self.assertEqual(got, {})
self.assertIsNone(run("Near.kmTo({points: [], lines: []}, -105, 40)"))
def test_across_the_antimeridian_and_at_the_poles_nothing_breaks(self):
fc = {"features": [feature("a", {"type": "LineString", "coordinates": [[179.5, 60], [-179.5, 60]]})]}
got = run("Near.distances(Near.shapesOf(input), 180, 60.0)", fc)["a"]
self.assertLess(got, 1)
got = run("Near.distances(Near.shapesOf(input), 0, 90)", fc)["a"]
self.assertTrue(math.isfinite(got))
@unittest.skipUnless(NODE, "node is not installed")
class OrderTest(unittest.TestCase):
def test_nearer_first_then_name_and_no_position_last(self):
rows = [{"km": 50, "name": "b"}, {"km": None, "name": "a"}, {"km": 50, "name": "a"}, {"km": 10, "name": "z"},
{"km": None, "name": "c"}]
got = run("input.slice().sort(Near.compare)", rows)
self.assertEqual([(r["km"], r["name"]) for r in got],
[(10, "z"), (50, "a"), (50, "b"), (None, "a"), (None, "c")])
def test_real_start_points_are_ordered_as_an_independent_haversine_orders_them(self):
recs = recordsmod.load_records(ROOT)
feats, pts = [], {}
for r in recs:
p = hike.start_point(r)
if p:
pts[r["id"]] = tuple(p)
feats.append(feature(r["id"], {"type": "MultiPoint", "coordinates": [p]}, sketch=True))
self.assertGreater(len(pts), 50)
for here in (DENVER, TORONTO):
got = run("Near.distances(Near.shapesOf(input), %s, %s)" % here, {"features": feats})
self.assertEqual(set(got), set(pts))
want = sorted(pts, key=lambda i: (haversine(here, pts[i]), i))
mine = sorted(got, key=lambda i: (round(got[i], 3), i))
self.assertEqual(mine[:10], want[:10])
for i in pts:
self.assertAlmostEqual(got[i], haversine(here, pts[i]), delta=0.5)
class WiringTest(unittest.TestCase):
def test_every_list_s_sort_control_ends_with_nearest_to_me(self):
for select in (home.sort_select(), home.sort_select(saved=True), home.sort_select(ranked="Length"),
home.sort_select(wholly=lambda r: True)):
self.assertTrue(select.rstrip().split("</select>")[0].rstrip().endswith('<option value="nearest">Nearest to me</option>'))
def test_the_position_is_never_written_to_the_address_or_to_storage(self):
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
text = f.read()
self.assertIn("if (key === defaultSortOf(root) || key === 'nearest') p.delete('sort')", text)
self.assertIn("sort.value !== 'nearest') p.set('sort', sort.value)", text)
self.assertIn("return key === 'nearest' ? '' : key;", text)
self.assertIn("p.get('sort') === 'nearest' ? '' :", text)
near = text[text.index("var nearAway = null;"):text.index("function applySortUI")]
for forbidden in ("localStorage", "sessionStorage", "writePref", "history.", "window.location", "XMLHttpRequest", "sendBeacon"):
self.assertNotIn(forbidden, near)
# the only request is for the overview geometry the maps use
self.assertEqual(near.count("fetch("), 1)
self.assertIn("fetch('/data/overview.geojson'", near)
self.assertEqual(near.count("getCurrentPosition("), 1)
def test_the_privacy_line_and_the_fallbacks_are_worded(self):
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
text = f.read()
for words in ("Your position stays in this browser: it is not stored, sent or put in the address.",
"Your position was not available, so the list is back in its earlier order.",
"no position on file"):
self.assertIn(words, text)
if __name__ == "__main__":
unittest.main()
+2 -1
View File
@@ -84,7 +84,8 @@ class SortKeysTest(unittest.TestCase):
self.assertIn('<span class="results-sort__label">Sort by</span>', select)
self.assertIn('<option value="length-asc" selected>Length, shortest first</option>', select)
self.assertEqual([m for m in re.findall(r'<option value="([^"]+)"', select)],
[k for k, _ in facets.SORTS])
[k for k, _ in facets.SORTS] + ["nearest"])
self.assertIn('<option value="nearest">Nearest to me</option>', select)
def test_old_address_keys_still_work(self):
for old, new in [("long", "length-desc"), ("short", "length-asc"),