Saved page: write a short ?s= link once a list passes ten trails

Up to ten trails the link stays ?t=id,id,... With more it is a version
character and a base64url bit set over the trails' permanent numbers
(trail-numbers.txt), 70 characters for any list instead of 1,013 for 49
trails. Both forms open for good; ?s= wins when both are there; a retired
or unknown number is ignored and a code that cannot be read shows the page's
existing no-trails state. A short link does not keep the order saved, so
that list opens A to Z.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 15:19:50 -07:00
1 parent 358f0c4928
commit 07b023f31b
3 files changed
+288 -12

No files matched your search

+89 -7
View File
@@ -295,10 +295,64 @@
}
syncSaved();
/* The short link to a saved list ---------------------------------------------
Up to SAVED_READABLE_MAX trails the link names them (?t=id,id,...); with more it is
?s=<code>, which does not grow with the list. The code is a bit set over the trails'
permanent numbers (trail-numbers.txt): bit N is 1 when trail N is in the list, packed
into bytes with bit 0 the least significant bit of byte 0, trailing zero bytes dropped,
written as base64url without padding after one version character, SAVED_CODE_VERSION.
A later format takes another version character; this one is read for good. The order
of a list is not kept. decode never throws: it gives null for a code it cannot read
(wrong version, bad characters, impossible length) and otherwise the numbers, in
ascending order. docs/schema.md describes it; test_short_links.py runs it under node. */
/* short-codes:begin */
var SAVED_READABLE_MAX = 10;
var SAVED_CODE_VERSION = '1';
var SavedCode = (function () {
var ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
var MAX_CODE = 2000;
function encode(numbers) {
var top = -1;
numbers.forEach(function (n) { if (n > top) top = n; });
var bytes = [];
for (var i = 0; i <= top >> 3; i++) bytes.push(0);
numbers.forEach(function (n) { bytes[n >> 3] |= 1 << (n & 7); });
var out = '';
for (var j = 0; j < bytes.length; j += 3) {
var b0 = bytes[j], b1 = j + 1 < bytes.length ? bytes[j + 1] : 0, b2 = j + 2 < bytes.length ? bytes[j + 2] : 0;
var chunk = [b0 >> 2, ((b0 & 3) << 4) | (b1 >> 4), ((b1 & 15) << 2) | (b2 >> 6), b2 & 63];
var keep = Math.min(bytes.length - j, 3) + 1;
for (var k = 0; k < keep; k++) out += ALPHABET.charAt(chunk[k]);
}
return SAVED_CODE_VERSION + out;
}
function decode(code) {
if (typeof code !== 'string' || code.length < 1 || code.length > MAX_CODE) return null;
if (code.charAt(0) !== SAVED_CODE_VERSION) return null;
var text = code.slice(1);
if (text.length % 4 === 1) return null;
var bytes = [], acc = 0, bits = 0;
for (var i = 0; i < text.length; i++) {
var v = ALPHABET.indexOf(text.charAt(i));
if (v < 0) return null;
acc = (acc << 6) | v;
bits += 6;
if (bits >= 8) { bits -= 8; bytes.push((acc >> bits) & 255); acc &= (1 << bits) - 1; }
}
var numbers = [];
bytes.forEach(function (b, at) {
for (var bit = 0; bit < 8; bit++) if (b & (1 << bit)) numbers.push(at * 8 + bit);
});
return numbers;
}
return { encode: encode, decode: decode };
})();
/* short-codes:end */
/* 1c. The Saved page ---------------------------------------------------------
/saved/ holds every trail's row, hidden (olt/saved.py). With no t= in the
address it shows the visitor's saved trails; with t=<id>,<id>,... it shows
that list, marked as from a link, and changes nothing until "Save these".
/saved/ holds every trail's row, hidden (olt/saved.py). With no t= or s= in the
address it shows the visitor's saved trails; with t=<id>,<id>,... or s=<code>
(the short link above) it shows that list, marked as from a link, and changes nothing until "Save these".
A link that holds the visitor's own list is shown as theirs. On their own
list a trail they unsave stays in place, dimmed, so it can be saved again;
trails saved meanwhile (in another tab) are added at the end. The map
@@ -325,11 +379,25 @@
var rows = {};
results.querySelectorAll('.entry[data-id]').forEach(function (li) { rows[li.dataset.id] = li; });
/* The trails' permanent numbers, from the build: the ids in number order, "-" for a retired one. */
var idAt = (page.dataset.savedNumbers || '').split(' ');
var numberOf = {};
idAt.forEach(function (id, n) { if (id && id !== '-') numberOf[id] = n; });
var params = new URLSearchParams(window.location.search);
var fromLink = params.has('t');
var shortLink = params.has('s'); /* ?s= wins over ?t= when both are there */
var fromLink = shortLink || params.has('t');
var linkIds = [];
var dropped = 0;
if (fromLink) {
if (shortLink) {
/* A number that is retired or unknown is ignored without a word; a code that cannot be
read lists nothing, which the page says as "None of the trails in this link...". */
var numbers = SavedCode.decode(params.get('s')) || [];
numbers.forEach(function (n) {
var id = idAt[n];
if (id && rows.hasOwnProperty(id)) linkIds.push(id);
});
} else if (fromLink) {
var seen = {};
(params.get('t') || '').split(',').forEach(function (id) {
id = id.trim().toLowerCase();
@@ -344,12 +412,26 @@
trail is unsaved a reload does not show the old list as someone's link. */
fromLink = false;
params.delete('t');
params.delete('s');
var rest = params.toString();
window.history.replaceState(null, '', window.location.pathname + (rest ? '?' + rest : '') + window.location.hash);
}
}
var shown = fromLink ? linkIds.slice() : readSaved();
var mapOn = false;
/* A short link does not keep the order the trails were saved in, so such a list opens
A to Z, the page's usual order, and its rows carry no saved order. */
var unordered = fromLink && shortLink;
if (unordered) results.dataset.defaultSort = 'name';
/* The link to a list of these ids: readable up to SAVED_READABLE_MAX, a short code after. */
function linkTo(ids) {
var query = '?t=' + ids.join(',');
if (ids.length > SAVED_READABLE_MAX && ids.every(function (id) { return numberOf.hasOwnProperty(id); })) {
query = '?s=' + SavedCode.encode(ids.map(function (id) { return numberOf[id]; }));
}
return window.location.origin + '/saved/' + query;
}
function plural(n, one, many) { return n + ' ' + (n === 1 ? one : many); }
@@ -379,7 +461,7 @@
var li = rows[id];
var listed = order.hasOwnProperty(id);
li.hidden = !listed;
if (listed) li.dataset.order = String(order[id]); else delete li.dataset.order;
if (listed && !unordered) li.dataset.order = String(order[id]); else delete li.dataset.order;
li.classList.toggle('is-unsaved', view === 'own' && listed && !ownSet[id]);
});
var n = fromLink ? linkIds.length : own.length;
@@ -391,7 +473,7 @@
var ids = fromLink ? linkIds : own;
share.hidden = view === 'none' || !ids.length;
url.textContent = window.location.origin + '/saved/?t=' + ids.join(',');
url.textContent = linkTo(ids);
var onMap = shown.filter(function (id) { return drawable[id]; });
if (fig) fig.hidden = !onMap.length;
+28 -5
View File
@@ -2,8 +2,12 @@
Saved trails are kept in the visitor's browser only: localStorage, key
lh-saved, the trail ids in the order saved (app.js). A link carries a list in
its own address, /saved/?t=<id>,<id>,..., so it opens the same list on any
device, in any browser, with nothing remembered.
its own address, so it opens the same list on any device, in any browser, with
nothing remembered. Up to ten trails the link names them, /saved/?t=<id>,<id>,...;
with more it is a short code, /saved/?s=<code>, a bit set over the trails' permanent
numbers (trail-numbers.txt). The page carries the numbers as data-saved-numbers on
its head: the trail ids in number order, "-" for a number whose trail is gone.
app.js (SavedCode) writes and reads both forms; docs/schema.md has the format.
The page is written like every other, so it cannot know the list. It holds
every trail's row, hidden (the same rows as the catalogue, about as heavy as
@@ -13,7 +17,7 @@ the home page's list; the hidden rows' logos are not fetched), and app.js
own list no t= in the address: the visitor's saved trails, the map
of them, and the link to them with a Copy link button
nothing saved no t=, nothing saved: how to save a trail, and a link to the trails
from a link t= in the address: that list, marked as from a link, with
from a link t= or s= in the address: that list, marked as from a link, with
"Save these" (adds it to the visitor's own) and a way to
their own list; ids that match no trail are dropped and
counted. A link holding the visitor's own list is shown as theirs.
@@ -21,19 +25,38 @@ the home page's list; the hidden rows' logos are not fetched), and app.js
Without JavaScript the page says that saved trails need it. It is not
indexed (layout noindex) and not in the sitemap (seo.all_paths).
"""
from . import common, home
import os
from . import common, home, records
from .markup import Markup
NUMBERS_FILE = "trail-numbers.txt"
PATH = "/saved/"
TITLE = "Saved trails"
DESCRIPTION = "The trails you saved, kept in this browser, and a link that opens the same list anywhere."
def trail_numbers(ids, root=records.ROOT):
"""The page's number list: the ids of the trails that exist, in registry order, one
entry per number, with "-" for a number whose trail is gone (retired). The index of an
entry is the trail's number. A trail with no line in the registry is left out, and the
script then writes the readable link for any list that holds it."""
here = set(ids)
with open(os.path.join(root, NUMBERS_FILE), encoding="utf-8") as f:
lines = [ln.rstrip("\n") for ln in f if ln.strip() and not ln.startswith("#")]
out = [ln if ln in here else "-" for ln in lines]
while out and out[-1] == "-":
out.pop()
return out
def saved_page(records, site):
"""(title, description, body) for /saved/."""
recs = sorted(records, key=home.sort_name)
numbers = " ".join(trail_numbers([r["id"] for r in recs]))
star = common.ICON_STAR
body = f"""<div class="page-head saved-head" data-saved-page>
body = f"""<div class="page-head saved-head" data-saved-page data-saved-numbers="{numbers}">
<div class="container">
<header class="titleblock"><div class="titleblock__text">
<h1 data-saved-title>{TITLE}</h1>
+171
View File
@@ -0,0 +1,171 @@
"""The Saved page's short links: the code app.js writes and reads (SavedCode, run under node, no
browser) and the numbers the built page carries. The page's behaviour in a browser was checked by hand.
The format: ?s=<version char "1"><base64url of the bit set over trail numbers>, bit N set when trail N
is in the list, bit 0 the least significant bit of byte 0, trailing zero bytes dropped, no padding.
Up to SAVED_READABLE_MAX trails the link stays ?t=id,id,... (docs/schema.md).
"""
import base64
import json
import os
import re
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.join(ROOT, "tools"))
import build_index # noqa: E402
import trail_numbers # noqa: E402
from olt import records, saved # noqa: E402
NODE = shutil.which("node")
OUT = os.path.join(WEB, ".cache", "test-site")
# The owner's own list of 49 trails, in the order saved: a real fixture.
OWNER = ("eastern-sierra-high-route,sierra-high-route,southern-sierra-high-route,uinta-highline,grand-moab-route,"
"beartooth-high-route,chinese-wall-circuit,bitterroots-80-mile-route,pfiffner-traverse,"
"sawtooth-wilderness-high-route,teton-crest,teton-range-traverse,toiyabe-crest,wasatch-traverse,"
"wind-river-high-route-dixon-wilson,wind-river-high-route-skurka,yosemite-high-route,"
"kings-canyon-high-basin-route,prescott-circle,big-seki-loop,high-sierra,john-muir,pacific-crest,"
"sierra-grand-traverse,great-western-divide-loop,tahoe-rim,tahoe-yosemite-trail,continental-divide,"
"great-divide-trail,timberline,wonderland,great-basin-trail,lowest-to-highest-route,mogollon-rim-trail,"
"wyoming-range,teton-crest-route,central-wind-rivers-loop,gospel-hump-loop,grand-sawtooth-loop,"
"grand-teton-loop,green-river-lakes-titcomb-basin-loop,hayduke-trail,heart-lake-two-ocean-plateau-loop,"
"middle-fork-trail,teton-wilderness-loop,thorofare-and-south-boundary-trail,alpine-trail-7,"
"solitude-loop,circle-of-solitude").split(",")
def code_source():
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
js = f.read()
return js[js.index("/* short-codes:begin */"):js.index("/* short-codes:end */")]
def node(expr, data=None):
"""Evaluate a JS expression with SavedCode in scope; `data` is bound to the JSON given."""
prog = code_source() + "\nvar data = JSON.parse(require('fs').readFileSync(0, 'utf8'));\n" + \
"process.stdout.write(JSON.stringify(" + expr + "));"
done = subprocess.run([NODE, "-e", prog], input=json.dumps(data), capture_output=True, text=True, check=True)
return json.loads(done.stdout)
def encode(numbers):
return node("SavedCode.encode(data)", numbers)
def decode(code):
return node("SavedCode.decode(data)", code)
def reference(numbers):
"""The code, written independently in Python from the format's description."""
if not numbers:
return "1"
raw = bytearray(max(numbers) // 8 + 1)
for n in numbers:
raw[n // 8] |= 1 << (n % 8)
return "1" + base64.urlsafe_b64encode(bytes(raw)).decode().rstrip("=")
@unittest.skipUnless(NODE, "node is not installed")
class CodeTest(unittest.TestCase):
def test_a_small_known_set(self):
# bits 0, 1 and 9: byte 0 = 0b00000011, byte 1 = 0b00000010 -> bytes 03 02 -> base64url "AwI"
self.assertEqual(encode([0, 1, 9]), "1AwI")
self.assertEqual(decode("1AwI"), [0, 1, 9])
def test_bit_zero_is_the_least_significant_bit_of_byte_zero(self):
self.assertEqual(encode([0]), "1AQ") # byte 0x01
self.assertEqual(encode([7]), "1gA") # byte 0x80
self.assertEqual(encode([8]), "1AAE") # bytes 00 01
def test_trailing_zero_bytes_are_dropped_and_leading_ones_kept(self):
self.assertEqual(encode([0, 8, 16]), "1AQEB") # three bytes, none dropped
self.assertEqual(encode([16]), "1AAAB") # zero bytes before the last set bit stay
self.assertEqual(decode("1AQAAAA"), [0]) # extra zero bytes on the way in are harmless
self.assertEqual(encode([]), "1")
def test_matches_the_reference_for_many_sets(self):
import random
rng = random.Random(7)
for size in (1, 2, 10, 11, 49, 220):
for _ in range(5):
nums = sorted(rng.sample(range(240), size))
code = encode(nums)
self.assertEqual(code, reference(nums))
self.assertEqual(decode(code), nums)
def test_round_trips_for_0_1_10_11_49_and_all_trails(self):
ids, _ = trail_numbers.read(ROOT)
for size in (0, 1, 10, 11, 49, len(ids)):
nums = list(range(size))
self.assertEqual(decode(encode(nums)), nums)
def test_order_and_repeats_in_the_input_do_not_matter(self):
self.assertEqual(encode([9, 1, 0, 9]), "1AwI")
def test_malformed_codes_give_null_and_never_throw(self):
for bad in ("", "2AwI", "AwI", "1Aw$", "1A", "1AwIAA", "1 AwI", "1AwI=", "1AwI==", "1+/", "x" * 10, "1" + "A" * 3000):
self.assertIsNone(decode(bad), repr(bad[:20]))
for odd in (None, 5, ["1AwI"], {}):
self.assertIsNone(decode(odd))
def test_the_threshold_is_one_named_constant(self):
self.assertEqual(node("SAVED_READABLE_MAX"), 10)
def test_the_owners_forty_nine_is_short(self):
ids, _ = trail_numbers.read(ROOT)
self.assertEqual(len(OWNER), 49)
nums = sorted(ids.index(i) for i in OWNER)
code = encode(nums)
self.assertEqual(decode(code), nums)
self.assertLess(len("https://longhikes.org/saved/?s=" + code), 80)
class NumbersOnThePageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
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)
with open(os.path.join(OUT, "saved", "index.html"), encoding="utf-8") as f:
cls.page = f.read()
def numbers(self):
m = re.search(r'data-saved-numbers="([^"]*)"', self.page)
self.assertTrue(m, "the Saved page carries no numbers")
return m.group(1).split(" ")
def test_every_record_has_its_number_on_the_page(self):
ids = build_index.trail_dirs(ROOT)
registry, problems = trail_numbers.read(ROOT)
self.assertEqual(problems, [])
carried = self.numbers()
for tid in ids:
self.assertEqual(carried[registry.index(tid)], tid, tid)
def test_a_retired_number_is_a_hyphen_and_the_list_has_no_trailing_hyphens(self):
ids = ["a", "b", "c"]
import tempfile
with tempfile.TemporaryDirectory() as d:
with open(os.path.join(d, saved.NUMBERS_FILE), "w", encoding="utf-8") as f:
f.write("# c\na\ngone\nb\nc\nalso-gone\n")
self.assertEqual(saved.trail_numbers(ids, d), ["a", "-", "b", "c"])
def test_the_page_stays_small(self):
# 220 ids once in number order; the same words are in the rows, so they compress away.
self.assertLess(len(re.search(r'data-saved-numbers="([^"]*)"', self.page).group(1)), 8000)
def test_the_owners_list_is_on_the_page(self):
carried = set(self.numbers())
for tid in OWNER:
self.assertIn(tid, carried)
if __name__ == "__main__":
unittest.main()