Let the owner change regions by place name, without a restart
The p2p node can now add and drop regions while running (SetRegions): topics, validators, subscriptions and per-region peer discovery start and stop with them, and a newly followed region catches up by sync. PUT /api/v1/regions (owner token) applies a change and the node saves it in regions.json, which wins over --region from then on. The owner's browser gets a "Regions" page: search a place by name (GeoNames cities, offline, CC BY 4.0), follow its cell plus any cell within about 40 km. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
Vendored
+382
-20
@@ -212,6 +212,31 @@ var de = {
|
||||
"own.login": "Anmelden",
|
||||
"own.loginBad": "Der Knoten hat den Token abgelehnt.",
|
||||
"own.logout": "Abmelden",
|
||||
"reg.title": "Regionen",
|
||||
"reg.intro": "Dein Knoten h\xE4lt die Anzeigen dieser Regionen bereit und gibt sie an andere weiter. Suche einen Ort, zum Beispiel Bonn oder Hamburg. Die \xC4nderung gilt sofort und bleibt nach einem Neustart erhalten.",
|
||||
"reg.search": "Ort suchen",
|
||||
"reg.placeholder": "z. B. Bonn, K\xF6ln, Hamburg",
|
||||
"reg.results": "Gefundene Orte",
|
||||
"reg.none": "Dazu habe ich keinen Ort gefunden. Pr\xFCfe die Schreibweise, oder gib unten ein Regionsk\xFCrzel ein.",
|
||||
"reg.noPlaces": "Die Ortsliste konnte nicht geladen werden. Du kannst unten Regionsk\xFCrzel eingeben.",
|
||||
"reg.cellsTitle": "Regionen rund um {place}",
|
||||
"reg.cellsHelp": "Eine Region ist ein Gebiet von etwa 100 bis 150 km Breite. Liegt der Ort nahe am Rand, kommt die Nachbarregion dazu, damit dir Anzeigen gleich hinter der Grenze nicht fehlen. Nimm den Haken heraus, was du nicht brauchst.",
|
||||
"reg.here": "hier",
|
||||
"reg.add": "Hinzuf\xFCgen",
|
||||
"reg.chosen": "Ausgew\xE4hlte Regionen",
|
||||
"reg.nothing": "Noch keine Region ausgew\xE4hlt.",
|
||||
"reg.remove": "{region} entfernen",
|
||||
"reg.codes": "Oder Regionsk\xFCrzel eingeben",
|
||||
"reg.codesHelp": "F\xFCr alle, die sie kennen: drei Zeichen wie u1j, mehrere mit Komma getrennt.",
|
||||
"reg.badCode": "\u201E{code}\u201C ist keine Region: es m\xFCssen genau 3 Zeichen sein (Ziffern und Buchstaben au\xDFer a, i, l, o).",
|
||||
"reg.needOne": "W\xE4hle mindestens eine Region.",
|
||||
"reg.tooMany": "Das sind zu viele Regionen (h\xF6chstens {max}).",
|
||||
"reg.save": "Speichern",
|
||||
"reg.saving": "Speichert \u2026",
|
||||
"reg.saved": "Gespeichert. Der Knoten folgt jetzt diesen Regionen.",
|
||||
"reg.failed": "Das hat nicht geklappt.",
|
||||
"reg.signedOut": "Du bist abgemeldet. Melde dich unter \u201EMeine Anzeigen\u201C neu an.",
|
||||
"reg.credit": "Ortsnamen: GeoNames (geonames.org), Lizenz CC BY 4.0.",
|
||||
"own.listings": "Deine Anzeigen",
|
||||
"own.none": "Dein Knoten hat keine aktiven Anzeigen.",
|
||||
"own.perMonth": "/ Monat",
|
||||
@@ -436,6 +461,31 @@ var en = {
|
||||
"own.login": "Sign in",
|
||||
"own.loginBad": "The node rejected the token.",
|
||||
"own.logout": "Sign out",
|
||||
"reg.title": "Regions",
|
||||
"reg.intro": "Your node keeps the listings of these regions and passes them on to others. Search for a place, for example Bonn or Hamburg. A change applies at once and survives a restart.",
|
||||
"reg.search": "Search for a place",
|
||||
"reg.placeholder": "e.g. Bonn, Cologne, Hamburg",
|
||||
"reg.results": "Places found",
|
||||
"reg.none": "I found no place for that. Check the spelling, or enter a region code below.",
|
||||
"reg.noPlaces": "The list of places could not be loaded. You can enter region codes below.",
|
||||
"reg.cellsTitle": "Regions around {place}",
|
||||
"reg.cellsHelp": "A region is an area roughly 100 to 150 km across. If the place is near an edge, the neighbouring region is included so you do not miss listings just across the border. Untick what you do not need.",
|
||||
"reg.here": "here",
|
||||
"reg.add": "Add",
|
||||
"reg.chosen": "Chosen regions",
|
||||
"reg.nothing": "No region chosen yet.",
|
||||
"reg.remove": "Remove {region}",
|
||||
"reg.codes": "Or enter region codes",
|
||||
"reg.codesHelp": "For those who know them: three characters like u1j, several separated by commas.",
|
||||
"reg.badCode": "\u201C{code}\u201D is not a region: it must be exactly 3 characters (digits and letters except a, i, l, o).",
|
||||
"reg.needOne": "Choose at least one region.",
|
||||
"reg.tooMany": "That is too many regions (at most {max}).",
|
||||
"reg.save": "Save",
|
||||
"reg.saving": "Saving \u2026",
|
||||
"reg.saved": "Saved. The node now follows these regions.",
|
||||
"reg.failed": "That did not work.",
|
||||
"reg.signedOut": "You are signed out. Sign in again under \u201CMy listings\u201D.",
|
||||
"reg.credit": "Place names: GeoNames (geonames.org), licence CC BY 4.0.",
|
||||
"own.listings": "Your listings",
|
||||
"own.none": "Your node has no active listings.",
|
||||
"own.perMonth": "/ month",
|
||||
@@ -711,7 +761,7 @@ function keepFresh(alive, run, ms = FOREGROUND_MS, doc = document) {
|
||||
schedule();
|
||||
}
|
||||
|
||||
// node_modules/@noble/ciphers/utils.js
|
||||
// ../../web/node_modules/@noble/ciphers/utils.js
|
||||
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
||||
function isBytes(a) {
|
||||
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
||||
@@ -890,7 +940,7 @@ function copyBytes(bytes2) {
|
||||
return Uint8Array.from(abytes(bytes2));
|
||||
}
|
||||
|
||||
// node_modules/@noble/ciphers/_arx.js
|
||||
// ../../web/node_modules/@noble/ciphers/_arx.js
|
||||
var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
|
||||
var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))();
|
||||
var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))();
|
||||
@@ -1020,7 +1070,7 @@ function createCipher(core, opts) {
|
||||
};
|
||||
}
|
||||
|
||||
// node_modules/@noble/ciphers/_poly1305.js
|
||||
// ../../web/node_modules/@noble/ciphers/_poly1305.js
|
||||
function u8to16(a, i) {
|
||||
return a[i++] & 255 | (a[i++] & 255) << 8;
|
||||
}
|
||||
@@ -1271,7 +1321,7 @@ var Poly1305 = class {
|
||||
};
|
||||
var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
|
||||
|
||||
// node_modules/@noble/ciphers/chacha.js
|
||||
// ../../web/node_modules/@noble/ciphers/chacha.js
|
||||
function chachaCore(s, k, n, out, cnt, rounds = 20) {
|
||||
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
@@ -1421,7 +1471,7 @@ var chacha20poly1305 = /* @__PURE__ */ wrapCipher(
|
||||
/* @__PURE__ */ _poly1305_aead(chacha20)
|
||||
);
|
||||
|
||||
// node_modules/@noble/hashes/_u64.js
|
||||
// ../../web/node_modules/@noble/hashes/_u64.js
|
||||
var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
|
||||
var _32n = /* @__PURE__ */ BigInt(32);
|
||||
function fromBig(n, le = false) {
|
||||
@@ -1464,7 +1514,7 @@ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0
|
||||
var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
|
||||
var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
|
||||
|
||||
// node_modules/@noble/hashes/utils.js
|
||||
// ../../web/node_modules/@noble/hashes/utils.js
|
||||
function isBytes2(a) {
|
||||
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
||||
}
|
||||
@@ -1629,7 +1679,7 @@ var oidNist = (suffix) => ({
|
||||
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
||||
});
|
||||
|
||||
// node_modules/@noble/hashes/_md.js
|
||||
// ../../web/node_modules/@noble/hashes/_md.js
|
||||
function Chi(a, b, c) {
|
||||
return a & b ^ ~a & c;
|
||||
}
|
||||
@@ -1760,7 +1810,7 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
|
||||
327033209
|
||||
]);
|
||||
|
||||
// node_modules/@noble/hashes/sha2.js
|
||||
// ../../web/node_modules/@noble/hashes/sha2.js
|
||||
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
||||
1116352408,
|
||||
1899447441,
|
||||
@@ -2157,7 +2207,7 @@ var sha512 = /* @__PURE__ */ createHasher(
|
||||
/* @__PURE__ */ oidNist(3)
|
||||
);
|
||||
|
||||
// node_modules/@noble/curves/utils.js
|
||||
// ../../web/node_modules/@noble/curves/utils.js
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
function aarray(item, title, inner = () => {
|
||||
}) {
|
||||
@@ -2278,7 +2328,7 @@ function validateObject(object, fields = {}, optFields = {}, title = "object") {
|
||||
iter(optFields, true);
|
||||
}
|
||||
|
||||
// node_modules/@noble/curves/abstract/modular.js
|
||||
// ../../web/node_modules/@noble/curves/abstract/modular.js
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
var _0n2 = /* @__PURE__ */ BigInt(0);
|
||||
var _1n2 = /* @__PURE__ */ BigInt(1);
|
||||
@@ -2708,7 +2758,7 @@ function Field(ORDER, opts = {}) {
|
||||
return new _Field(ORDER, opts);
|
||||
}
|
||||
|
||||
// node_modules/@noble/curves/abstract/curve.js
|
||||
// ../../web/node_modules/@noble/curves/abstract/curve.js
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
var _0n3 = /* @__PURE__ */ BigInt(0);
|
||||
var _1n3 = /* @__PURE__ */ BigInt(1);
|
||||
@@ -3096,7 +3146,7 @@ function createKeygen(randomSecretKey, getPublicKey) {
|
||||
};
|
||||
}
|
||||
|
||||
// node_modules/@noble/curves/abstract/edwards.js
|
||||
// ../../web/node_modules/@noble/curves/abstract/edwards.js
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
var _0n4 = /* @__PURE__ */ BigInt(0);
|
||||
var _1n4 = /* @__PURE__ */ BigInt(1);
|
||||
@@ -3548,7 +3598,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
// node_modules/@noble/curves/abstract/montgomery.js
|
||||
// ../../web/node_modules/@noble/curves/abstract/montgomery.js
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
var _0n5 = /* @__PURE__ */ BigInt(0);
|
||||
var _1n5 = /* @__PURE__ */ BigInt(1);
|
||||
@@ -3696,7 +3746,7 @@ function montgomery(curveDef) {
|
||||
});
|
||||
}
|
||||
|
||||
// node_modules/@noble/curves/ed25519.js
|
||||
// ../../web/node_modules/@noble/curves/ed25519.js
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
var _0n6 = /* @__PURE__ */ BigInt(0);
|
||||
var _1n6 = /* @__PURE__ */ BigInt(1);
|
||||
@@ -3797,7 +3847,7 @@ var x25519 = /* @__PURE__ */ (() => {
|
||||
});
|
||||
})();
|
||||
|
||||
// node_modules/@noble/hashes/hmac.js
|
||||
// ../../web/node_modules/@noble/hashes/hmac.js
|
||||
var _HMAC = class {
|
||||
oHash;
|
||||
iHash;
|
||||
@@ -3874,7 +3924,7 @@ var hmac = /* @__PURE__ */ (() => {
|
||||
return hmac_;
|
||||
})();
|
||||
|
||||
// node_modules/@noble/hashes/hkdf.js
|
||||
// ../../web/node_modules/@noble/hashes/hkdf.js
|
||||
var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
|
||||
var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
|
||||
function expand(hash, prk, info, length = 32, _recycled) {
|
||||
@@ -4815,6 +4865,9 @@ async function putAddress(listing, a) {
|
||||
async function deleteAddress(listing) {
|
||||
await call("DELETE", `/api/v1/listings/${e(listing)}/address`);
|
||||
}
|
||||
async function setRegions(regions) {
|
||||
return (await call("PUT", "/api/v1/regions", { regions })).regions;
|
||||
}
|
||||
async function createListing(d) {
|
||||
return await call("POST", "/api/v1/listings", d);
|
||||
}
|
||||
@@ -4885,7 +4938,7 @@ async function showOwner(listingId, thread) {
|
||||
let threads = [];
|
||||
let msgs = [];
|
||||
let filter = "all";
|
||||
let loaded2 = false;
|
||||
let loaded3 = false;
|
||||
const notice = h("p", { class: "error", role: "alert" });
|
||||
const listingsBox = h("div", { class: "olist" });
|
||||
const listingsPane = h(
|
||||
@@ -4894,6 +4947,7 @@ async function showOwner(listingId, thread) {
|
||||
h("h2", { class: "pane-title" }, t("own.listings")),
|
||||
h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))),
|
||||
listingsBox,
|
||||
h("p", null, h("a", { class: "btn", href: "#/mine/regions" }, t("reg.title"))),
|
||||
h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout")))
|
||||
);
|
||||
const reqTitle = h("h2", { class: "pane-title" });
|
||||
@@ -4937,7 +4991,7 @@ async function showOwner(listingId, thread) {
|
||||
const kindLabel = (k) => k === "rent" || k === "sale" ? t(`kind.${k}`) : k ?? "";
|
||||
function renderListings() {
|
||||
clear(listingsBox);
|
||||
if (loaded2 && mine2.length === 0) listingsBox.append(h("p", { class: "muted" }, t("own.none")));
|
||||
if (loaded3 && mine2.length === 0) listingsBox.append(h("p", { class: "muted" }, t("own.none")));
|
||||
for (const m of mine2) {
|
||||
const sub = [kindLabel(m.kind), m.price ? price({ price: m.price }) : ""].filter(Boolean).join(" \xB7 ");
|
||||
listingsBox.append(
|
||||
@@ -4994,7 +5048,7 @@ async function showOwner(listingId, thread) {
|
||||
}
|
||||
const shown = threads.filter((x) => filter === "all" || (filter === "reply" ? x.needs_reply : x.hidden > 0));
|
||||
clear(reqBox);
|
||||
if (loaded2 && shown.length === 0) reqBox.append(h("p", { class: "muted" }, t("own.noMatch")));
|
||||
if (loaded3 && shown.length === 0) reqBox.append(h("p", { class: "muted" }, t("own.noMatch")));
|
||||
for (const th of shown) {
|
||||
reqBox.append(
|
||||
h(
|
||||
@@ -5047,7 +5101,7 @@ async function showOwner(listingId, thread) {
|
||||
}
|
||||
if (gen !== state.generation) return;
|
||||
notice.textContent = "";
|
||||
loaded2 = true;
|
||||
loaded3 = true;
|
||||
renderAll();
|
||||
}
|
||||
renderListings();
|
||||
@@ -5679,6 +5733,313 @@ async function showPublish(editId) {
|
||||
syncKind();
|
||||
}
|
||||
|
||||
// src/places.ts
|
||||
function fold(s) {
|
||||
return s.normalize("NFD").replace(/\p{M}/gu, "").replace(/ß/g, "ss").toLowerCase();
|
||||
}
|
||||
function unTranslit(s) {
|
||||
return s.replace(/ae/g, "a").replace(/oe/g, "o").replace(/ue/g, "u");
|
||||
}
|
||||
function parsePlaces(tsv) {
|
||||
const out = [];
|
||||
for (const line of tsv.split("\n")) {
|
||||
if (!line) continue;
|
||||
const [name, ascii, lat, lon, cc, pop, alt] = line.split(" ");
|
||||
if (!name || lat === void 0 || lon === void 0) continue;
|
||||
const alts = alt ? alt.split("|") : [];
|
||||
const keys = [name, ...alts].map(fold);
|
||||
if (ascii) keys.push(fold(ascii));
|
||||
out.push({ name, lat: Number(lat), lon: Number(lon), cc: cc ?? "", population: Number(pop) || 0, alts, keys });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function score(key, q) {
|
||||
if (key === q) return 0;
|
||||
if (key.startsWith(q)) return 1;
|
||||
if (key.split(/[\s-]+/).some((w) => w.startsWith(q))) return 2;
|
||||
return q.length >= 3 && key.includes(q) ? 3 : 4;
|
||||
}
|
||||
function searchPlaces(places, query, limit = 8) {
|
||||
const q1 = fold(query.trim());
|
||||
if (q1.length < 2) return [];
|
||||
const qs = [.../* @__PURE__ */ new Set([q1, unTranslit(q1)])];
|
||||
const hits = [];
|
||||
for (const p of places) {
|
||||
let best = 4;
|
||||
let bestKey = 0;
|
||||
for (let i = 0; i < p.keys.length; i++) {
|
||||
for (const q of qs) {
|
||||
const s = score(p.keys[i], q);
|
||||
if (s < best) [best, bestKey] = [s, i];
|
||||
}
|
||||
}
|
||||
if (best < 4) {
|
||||
const matched = bestKey >= 1 && bestKey <= p.alts.length ? p.alts[bestKey - 1] : null;
|
||||
hits.push({ m: { place: p, matched }, s: best });
|
||||
}
|
||||
}
|
||||
hits.sort((a, b) => a.s - b.s || b.m.place.population - a.m.place.population);
|
||||
return hits.slice(0, limit).map((h2) => h2.m);
|
||||
}
|
||||
var KM_PER_DEGREE = 111.2;
|
||||
function cellsNear(lat, lon, km = 40) {
|
||||
const cell = (la, lo) => encodeGeohash(Math.max(-89.999, Math.min(89.999, la)), ((lo + 180) % 360 + 360) % 360 - 180, 3);
|
||||
const out = [cell(lat, lon)];
|
||||
const dLat = 1 / KM_PER_DEGREE;
|
||||
const dLon = 1 / (KM_PER_DEGREE * Math.max(0.05, Math.cos(lat * Math.PI / 180)));
|
||||
for (const r of [km / 2, km]) {
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const a = i / 16 * 2 * Math.PI;
|
||||
const c = cell(lat + Math.sin(a) * r * dLat, lon + Math.cos(a) * r * dLon);
|
||||
if (!out.includes(c)) out.push(c);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function biggestPlaceByCell(places) {
|
||||
const by = /* @__PURE__ */ new Map();
|
||||
for (const p of places) {
|
||||
const c = encodeGeohash(p.lat, p.lon, 3);
|
||||
const cur = by.get(c);
|
||||
if (!cur || p.population > cur.population) by.set(c, p);
|
||||
}
|
||||
return by;
|
||||
}
|
||||
var loaded2 = null;
|
||||
function loadPlaces() {
|
||||
loaded2 ??= fetch("places.tsv").then((r) => {
|
||||
if (!r.ok) throw new Error(`${r.status}`);
|
||||
return r.text();
|
||||
}).then(parsePlaces).catch((e2) => {
|
||||
loaded2 = null;
|
||||
throw e2;
|
||||
});
|
||||
return loaded2;
|
||||
}
|
||||
|
||||
// src/regions.ts
|
||||
var CODE = /^[0-9bcdefghjkmnpqrstuvwxyz]{3}$/;
|
||||
var MAX_REGIONS = 20;
|
||||
function countryName(cc) {
|
||||
try {
|
||||
return new Intl.DisplayNames([lang], { type: "region" }).of(cc) ?? cc;
|
||||
} catch {
|
||||
return cc;
|
||||
}
|
||||
}
|
||||
function errText(e2) {
|
||||
if (e2 instanceof Unauthorized) return t("reg.signedOut");
|
||||
if (e2 && typeof e2 === "object" && "message" in e2) return String(e2.message);
|
||||
return typeof e2 === "string" ? e2 : t("reg.failed");
|
||||
}
|
||||
function regionPicker(opts) {
|
||||
const chosen = [...opts.initial];
|
||||
let places = [];
|
||||
let biggest = /* @__PURE__ */ new Map();
|
||||
const label2 = (code) => {
|
||||
const p = biggest.get(code);
|
||||
return p ? `${code} \xB7 ${p.name}` : code;
|
||||
};
|
||||
const chips = h("ul", { class: "rp-chips", "aria-label": t("reg.chosen") });
|
||||
const drawChips = () => {
|
||||
clear(chips);
|
||||
if (chosen.length === 0) append(chips, [h("li", { class: "muted" }, t("reg.nothing"))]);
|
||||
for (const code of chosen) {
|
||||
append(chips, [
|
||||
h(
|
||||
"li",
|
||||
{ class: "rp-chip" },
|
||||
h("span", null, label2(code)),
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
class: "rp-chip-x",
|
||||
"aria-label": t("reg.remove", { region: label2(code) }),
|
||||
onclick: () => {
|
||||
chosen.splice(chosen.indexOf(code), 1);
|
||||
drawChips();
|
||||
}
|
||||
},
|
||||
"\xD7"
|
||||
)
|
||||
)
|
||||
]);
|
||||
}
|
||||
};
|
||||
const results = h("ul", { class: "rp-results", role: "listbox", "aria-label": t("reg.results") });
|
||||
const cellsBox = h("div", { class: "rp-cells" });
|
||||
const hint = h("p", { class: "muted small", "aria-live": "polite" });
|
||||
const showCells = (place) => {
|
||||
clear(cellsBox);
|
||||
clear(results);
|
||||
const cells = cellsNear(place.lat, place.lon);
|
||||
const boxes = cells.map((code, i) => {
|
||||
const box = h("input", { type: "checkbox", name: `cell-${code}`, checked: true, "aria-label": code });
|
||||
return { code, box, row: h("label", { class: "rp-cell" }, box, h("span", null, `${label2(code)}${i === 0 ? ` (${t("reg.here")})` : ""}`)) };
|
||||
});
|
||||
append(cellsBox, [
|
||||
h("h2", null, t("reg.cellsTitle", { place: place.name })),
|
||||
h("p", { class: "muted small" }, t("reg.cellsHelp")),
|
||||
...boxes.map((b) => b.row),
|
||||
h(
|
||||
"div",
|
||||
{ class: "actions" },
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
class: "btn",
|
||||
onclick: () => {
|
||||
for (const b of boxes) if (b.box.checked && !chosen.includes(b.code)) chosen.push(b.code);
|
||||
clear(cellsBox);
|
||||
search2.value = "";
|
||||
drawChips();
|
||||
}
|
||||
},
|
||||
t("reg.add")
|
||||
)
|
||||
)
|
||||
]);
|
||||
};
|
||||
const showMatches = (matches) => {
|
||||
clear(results);
|
||||
for (const m of matches) {
|
||||
const p = m.place;
|
||||
append(results, [
|
||||
h(
|
||||
"li",
|
||||
{ role: "option" },
|
||||
h(
|
||||
"button",
|
||||
{ type: "button", class: "rp-result", onclick: () => showCells(p) },
|
||||
h("strong", null, p.name),
|
||||
m.matched ? ` (${m.matched})` : "",
|
||||
h("span", { class: "muted" }, ` \xB7 ${countryName(p.cc)}`)
|
||||
)
|
||||
)
|
||||
]);
|
||||
}
|
||||
};
|
||||
const search2 = h("input", {
|
||||
type: "search",
|
||||
name: "place",
|
||||
autocomplete: "off",
|
||||
spellcheck: "false",
|
||||
placeholder: t("reg.placeholder"),
|
||||
"aria-label": t("reg.search"),
|
||||
disabled: true
|
||||
// until the list of places has loaded: an early search would find nothing
|
||||
});
|
||||
search2.addEventListener("input", () => {
|
||||
clear(cellsBox);
|
||||
const q = search2.value;
|
||||
if (q.trim().length < 2) {
|
||||
clear(results);
|
||||
hint.textContent = "";
|
||||
return;
|
||||
}
|
||||
const found = searchPlaces(places, q);
|
||||
showMatches(found);
|
||||
hint.textContent = found.length === 0 ? t("reg.none") : "";
|
||||
});
|
||||
void loadPlaces().then(
|
||||
(p) => {
|
||||
places = p;
|
||||
biggest = biggestPlaceByCell(p);
|
||||
search2.disabled = false;
|
||||
drawChips();
|
||||
},
|
||||
() => {
|
||||
hint.textContent = t("reg.noPlaces");
|
||||
}
|
||||
);
|
||||
const codes = h("input", { type: "text", name: "regions", placeholder: "u1j", autocomplete: "off", spellcheck: "false", "aria-label": t("reg.codes") });
|
||||
const problem = h("p", { class: "error", role: "alert" });
|
||||
const go = h("button", { type: "submit", class: "btn primary" }, opts.submitLabel);
|
||||
const form = h(
|
||||
"form",
|
||||
{
|
||||
class: "stack regions",
|
||||
onsubmit: (ev) => {
|
||||
ev.preventDefault();
|
||||
problem.textContent = "";
|
||||
for (const raw of codes.value.split(/[\s,;]+/).filter(Boolean)) {
|
||||
const code = raw.toLowerCase();
|
||||
if (!CODE.test(code)) {
|
||||
problem.textContent = t("reg.badCode", { code: raw });
|
||||
return;
|
||||
}
|
||||
if (!chosen.includes(code)) chosen.push(code);
|
||||
}
|
||||
codes.value = "";
|
||||
drawChips();
|
||||
if (chosen.length === 0) {
|
||||
problem.textContent = t("reg.needOne");
|
||||
return;
|
||||
}
|
||||
if (chosen.length > MAX_REGIONS) {
|
||||
problem.textContent = t("reg.tooMany", { max: MAX_REGIONS });
|
||||
return;
|
||||
}
|
||||
go.disabled = true;
|
||||
const label3 = go.textContent;
|
||||
go.textContent = t("reg.saving");
|
||||
opts.onSubmit([...chosen]).catch((e2) => {
|
||||
problem.textContent = errText(e2);
|
||||
go.disabled = false;
|
||||
go.textContent = label3;
|
||||
});
|
||||
}
|
||||
},
|
||||
h("label", null, t("reg.search"), search2),
|
||||
hint,
|
||||
results,
|
||||
cellsBox,
|
||||
h("h2", null, t("reg.chosen")),
|
||||
chips,
|
||||
h("label", null, t("reg.codes"), codes),
|
||||
h("p", { class: "muted small" }, t("reg.codesHelp")),
|
||||
problem,
|
||||
h("div", { class: "actions" }, go),
|
||||
h("p", { class: "muted small" }, t("reg.credit"))
|
||||
);
|
||||
drawChips();
|
||||
return form;
|
||||
}
|
||||
function showRegions(message = "") {
|
||||
const root = document.getElementById("app");
|
||||
document.body.classList.remove("wide");
|
||||
clear(root);
|
||||
if (!getToken()) {
|
||||
location.hash = "#/mine";
|
||||
return;
|
||||
}
|
||||
const picker = regionPicker({
|
||||
initial: state.node?.regions ?? [],
|
||||
submitLabel: t("reg.save"),
|
||||
onSubmit: async (regions) => {
|
||||
const now = await setRegions(regions);
|
||||
if (state.node) state.node.regions = now;
|
||||
const statusEl2 = document.getElementById("status");
|
||||
if (statusEl2 && state.node) {
|
||||
statusEl2.textContent = t("status.line", { listings: state.node.listings, peers: state.node.peers, regions: now.join(", ") });
|
||||
}
|
||||
showRegions(t("reg.saved"));
|
||||
}
|
||||
});
|
||||
append(root, [
|
||||
h(
|
||||
"section",
|
||||
{ class: "panel" },
|
||||
h("h1", null, t("reg.title")),
|
||||
h("p", { class: "muted" }, t("reg.intro")),
|
||||
h("p", { class: "ok", role: "status" }, message),
|
||||
picker
|
||||
)
|
||||
]);
|
||||
}
|
||||
|
||||
// src/main.ts
|
||||
var PAGE = 20;
|
||||
var GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
|
||||
@@ -5980,6 +6341,7 @@ function route() {
|
||||
} else if (m) void showDetail(m[1], m[2]);
|
||||
else if (c) void showConversation(c[1], c[2], c[3]);
|
||||
else if (path === "/messages") showInbox();
|
||||
else if (path === "/mine/regions") showRegions();
|
||||
else if (path === "/mine/new") void showPublish();
|
||||
else if (edit) void showPublish(edit[1]);
|
||||
else if (own) void showOwner(own[1], own[2]);
|
||||
|
||||
Vendored
+34247
File diff suppressed because it is too large
Load Diff
Vendored
+10
@@ -269,6 +269,16 @@ label.check { flex-direction: row; align-items: center; gap: 8px; }
|
||||
.badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||
.badge.warn { color: var(--warn); background: var(--warn-bg); }
|
||||
.badge.muted { color: var(--muted); background: transparent; border: 1px solid var(--line); }
|
||||
/* the region picker */
|
||||
.rp-chips, .rp-results { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.rp-results { flex-direction: column; flex-wrap: nowrap; }
|
||||
.rp-chip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 4px 2px 10px; background: var(--bg); border: 1px solid var(--line); border-radius: 999px; }
|
||||
.rp-chip-x { border: 0; background: none; cursor: pointer; font-size: 1.1rem; line-height: 1; padding: 2px 8px; color: inherit; }
|
||||
.rp-result { width: 100%; text-align: left; background: none; border: 1px solid transparent; border-radius: 6px; padding: 8px; cursor: pointer; color: inherit; font: inherit; }
|
||||
.rp-result:hover, .rp-result:focus-visible { border-color: var(--line); background: var(--bg); }
|
||||
.rp-cells { display: grid; gap: 6px; }
|
||||
.stack label.rp-cell { flex-direction: row; align-items: center; gap: 8px; color: inherit; font-size: 1rem; }
|
||||
p.ok { color: var(--ok); }
|
||||
.chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
|
||||
.chip {
|
||||
min-height: 2.25rem;
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// Builds static/places.tsv, the offline list of place names the region picker
|
||||
// searches, from GeoNames' cities15000.txt (https://download.geonames.org/export/dump/).
|
||||
//
|
||||
// curl -O https://download.geonames.org/export/dump/cities15000.zip && unzip cities15000.zip
|
||||
// node scripts/places.mjs cities15000.txt > static/places.tsv
|
||||
//
|
||||
// The data is © GeoNames, licensed CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/):
|
||||
// the app credits it where places are searched. The output is committed, so
|
||||
// building the UI needs no download.
|
||||
//
|
||||
// One place per line: name, ASCII name, lat, lon, country, population, and for
|
||||
// larger cities the other Latin-script names people use (Köln: Cologne, Colonia).
|
||||
// Searching works offline; nothing about where a person looks leaves the device.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const file = process.argv[2];
|
||||
if (!file) {
|
||||
console.error("usage: node scripts/places.mjs cities15000.txt > static/places.tsv");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const LATIN = /^[\p{Script=Latin}\p{M}\p{Zs}'.\-]+$/u;
|
||||
const ALT_MIN_POPULATION = 100_000; // exonyms matter for big cities only
|
||||
const ALT_MAX = 30;
|
||||
|
||||
// German names that GeoNames' English-named entries do not carry ("Munich" has
|
||||
// no "München"), keyed by "English name|country".
|
||||
const GERMAN = {
|
||||
"Munich|DE": "München", "Nuremberg|DE": "Nürnberg", "Prague|CZ": "Prag", "Geneva|CH": "Genf",
|
||||
"Milan|IT": "Mailand", "Rome|IT": "Rom", "Florence|IT": "Florenz", "Venice|IT": "Venedig",
|
||||
"Naples|IT": "Neapel", "Turin|IT": "Turin", "Warsaw|PL": "Warschau", "Copenhagen|DK": "Kopenhagen",
|
||||
"Brussels|BE": "Brüssel", "Lisbon|PT": "Lissabon", "Athens|GR": "Athen", "Vienna|AT": "Wien",
|
||||
"Cologne|DE": "Köln", "Hanover|DE": "Hannover", "Saint Petersburg|RU": "Sankt Petersburg",
|
||||
"Moscow|RU": "Moskau", "Kyiv|UA": "Kiew", "Bucharest|RO": "Bukarest", "Belgrade|RS": "Belgrad",
|
||||
"Seville|ES": "Sevilla", "Basel|CH": "Basel", "Bern|CH": "Bern", "Lucerne|CH": "Luzern",
|
||||
"Strasbourg|FR": "Straßburg", "Luxembourg|LU": "Luxemburg", "Antwerp|BE": "Antwerpen",
|
||||
};
|
||||
|
||||
const fold = (s) =>s.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
|
||||
const out = [];
|
||||
|
||||
for (const line of readFileSync(file, "utf8").split("\n")) {
|
||||
if (!line) continue;
|
||||
const f = line.split("\t");
|
||||
const [, name, ascii, alternates, lat, lon, , , cc] = f;
|
||||
const population = Number(f[14]);
|
||||
let alts = [];
|
||||
if (population >= ALT_MIN_POPULATION) {
|
||||
const have = new Set([fold(name), fold(ascii)]);
|
||||
for (const a of alternates.split(",")) {
|
||||
// Skip other scripts, codes ("CGN"), romanisations with apostrophes
|
||||
// ("K'oln"), lower-case transliterations ("klwn"), and what we already have.
|
||||
if (a.length < 4 || !LATIN.test(a) || a === a.toUpperCase() || a.includes("'")) continue;
|
||||
if (a[0] !== a[0].toUpperCase() || have.has(fold(a))) continue;
|
||||
have.add(fold(a));
|
||||
alts.push(a);
|
||||
}
|
||||
// Names without spaces first (Cologne before "Colonia Claudia Ara Agrippinensium").
|
||||
alts = alts.sort((x, y) => x.split(" ").length - y.split(" ").length || x.length - y.length).slice(0, ALT_MAX);
|
||||
}
|
||||
const de = GERMAN[`${name}|${cc}`];
|
||||
if (de && fold(de) !== fold(name) && !alts.some((a) => fold(a) === fold(de))) alts.unshift(de);
|
||||
out.push([name, ascii === name ? "" : ascii, Number(lat).toFixed(2), Number(lon).toFixed(2), cc, population, alts.join("|")].join("\t"));
|
||||
}
|
||||
|
||||
process.stdout.write(out.join("\n") + "\n");
|
||||
@@ -115,6 +115,33 @@ const de = {
|
||||
"own.login": "Anmelden",
|
||||
"own.loginBad": "Der Knoten hat den Token abgelehnt.",
|
||||
"own.logout": "Abmelden",
|
||||
"reg.title": "Regionen",
|
||||
"reg.intro":
|
||||
"Dein Knoten hält die Anzeigen dieser Regionen bereit und gibt sie an andere weiter. Suche einen Ort, zum Beispiel Bonn oder Hamburg. Die Änderung gilt sofort und bleibt nach einem Neustart erhalten.",
|
||||
"reg.search": "Ort suchen",
|
||||
"reg.placeholder": "z. B. Bonn, Köln, Hamburg",
|
||||
"reg.results": "Gefundene Orte",
|
||||
"reg.none": "Dazu habe ich keinen Ort gefunden. Prüfe die Schreibweise, oder gib unten ein Regionskürzel ein.",
|
||||
"reg.noPlaces": "Die Ortsliste konnte nicht geladen werden. Du kannst unten Regionskürzel eingeben.",
|
||||
"reg.cellsTitle": "Regionen rund um {place}",
|
||||
"reg.cellsHelp":
|
||||
"Eine Region ist ein Gebiet von etwa 100 bis 150 km Breite. Liegt der Ort nahe am Rand, kommt die Nachbarregion dazu, damit dir Anzeigen gleich hinter der Grenze nicht fehlen. Nimm den Haken heraus, was du nicht brauchst.",
|
||||
"reg.here": "hier",
|
||||
"reg.add": "Hinzufügen",
|
||||
"reg.chosen": "Ausgewählte Regionen",
|
||||
"reg.nothing": "Noch keine Region ausgewählt.",
|
||||
"reg.remove": "{region} entfernen",
|
||||
"reg.codes": "Oder Regionskürzel eingeben",
|
||||
"reg.codesHelp": "Für alle, die sie kennen: drei Zeichen wie u1j, mehrere mit Komma getrennt.",
|
||||
"reg.badCode": "„{code}“ ist keine Region: es müssen genau 3 Zeichen sein (Ziffern und Buchstaben außer a, i, l, o).",
|
||||
"reg.needOne": "Wähle mindestens eine Region.",
|
||||
"reg.tooMany": "Das sind zu viele Regionen (höchstens {max}).",
|
||||
"reg.save": "Speichern",
|
||||
"reg.saving": "Speichert …",
|
||||
"reg.saved": "Gespeichert. Der Knoten folgt jetzt diesen Regionen.",
|
||||
"reg.failed": "Das hat nicht geklappt.",
|
||||
"reg.signedOut": "Du bist abgemeldet. Melde dich unter „Meine Anzeigen“ neu an.",
|
||||
"reg.credit": "Ortsnamen: GeoNames (geonames.org), Lizenz CC BY 4.0.",
|
||||
"own.listings": "Deine Anzeigen",
|
||||
"own.none": "Dein Knoten hat keine aktiven Anzeigen.",
|
||||
"own.perMonth": "/ Monat",
|
||||
@@ -362,6 +389,33 @@ const en: Record<keyof typeof de, string> = {
|
||||
"own.login": "Sign in",
|
||||
"own.loginBad": "The node rejected the token.",
|
||||
"own.logout": "Sign out",
|
||||
"reg.title": "Regions",
|
||||
"reg.intro":
|
||||
"Your node keeps the listings of these regions and passes them on to others. Search for a place, for example Bonn or Hamburg. A change applies at once and survives a restart.",
|
||||
"reg.search": "Search for a place",
|
||||
"reg.placeholder": "e.g. Bonn, Cologne, Hamburg",
|
||||
"reg.results": "Places found",
|
||||
"reg.none": "I found no place for that. Check the spelling, or enter a region code below.",
|
||||
"reg.noPlaces": "The list of places could not be loaded. You can enter region codes below.",
|
||||
"reg.cellsTitle": "Regions around {place}",
|
||||
"reg.cellsHelp":
|
||||
"A region is an area roughly 100 to 150 km across. If the place is near an edge, the neighbouring region is included so you do not miss listings just across the border. Untick what you do not need.",
|
||||
"reg.here": "here",
|
||||
"reg.add": "Add",
|
||||
"reg.chosen": "Chosen regions",
|
||||
"reg.nothing": "No region chosen yet.",
|
||||
"reg.remove": "Remove {region}",
|
||||
"reg.codes": "Or enter region codes",
|
||||
"reg.codesHelp": "For those who know them: three characters like u1j, several separated by commas.",
|
||||
"reg.badCode": "“{code}” is not a region: it must be exactly 3 characters (digits and letters except a, i, l, o).",
|
||||
"reg.needOne": "Choose at least one region.",
|
||||
"reg.tooMany": "That is too many regions (at most {max}).",
|
||||
"reg.save": "Save",
|
||||
"reg.saving": "Saving …",
|
||||
"reg.saved": "Saved. The node now follows these regions.",
|
||||
"reg.failed": "That did not work.",
|
||||
"reg.signedOut": "You are signed out. Sign in again under “My listings”.",
|
||||
"reg.credit": "Place names: GeoNames (geonames.org), licence CC BY 4.0.",
|
||||
"own.listings": "Your listings",
|
||||
"own.none": "Your node has no active listings.",
|
||||
"own.perMonth": "/ month",
|
||||
|
||||
@@ -7,6 +7,7 @@ import { contactPanel, showConversation, showInbox } from "./chat.ts";
|
||||
import { showOwner } from "./owner.ts";
|
||||
import { getToken, setToken } from "./ownerApi.ts";
|
||||
import { showPublish } from "./publish.ts";
|
||||
import { showRegions } from "./regions.ts";
|
||||
import { state, verifyOpts } from "./state.ts";
|
||||
import { verifyListing, type Listing, type Verdict } from "./verify.ts";
|
||||
|
||||
@@ -357,6 +358,7 @@ function route(): void {
|
||||
} else if (m) void showDetail(m[1]!, m[2]!);
|
||||
else if (c) void showConversation(c[1]!, c[2]!, c[3]!);
|
||||
else if (path === "/messages") showInbox();
|
||||
else if (path === "/mine/regions") showRegions();
|
||||
else if (path === "/mine/new") void showPublish();
|
||||
else if (edit) void showPublish(edit[1]);
|
||||
else if (own) void showOwner(own[1], own[2]);
|
||||
|
||||
@@ -90,6 +90,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
|
||||
h("h2", { class: "pane-title" }, t("own.listings")),
|
||||
h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))),
|
||||
listingsBox,
|
||||
h("p", null, h("a", { class: "btn", href: "#/mine/regions" }, t("reg.title"))),
|
||||
h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout"))),
|
||||
);
|
||||
|
||||
|
||||
@@ -176,6 +176,11 @@ export async function deleteAddress(listing: string): Promise<void> {
|
||||
}
|
||||
|
||||
/** Publishes a new listing. The node signs it and mines its proof-of-work, which takes a few seconds. */
|
||||
/** Makes the node follow exactly these regions, now and after a restart; returns what it follows. */
|
||||
export async function setRegions(regions: string[]): Promise<string[]> {
|
||||
return ((await call("PUT", "/api/v1/regions", { regions })) as { regions: string[] }).regions;
|
||||
}
|
||||
|
||||
export async function createListing(d: Draft): Promise<Listing> {
|
||||
return (await call("POST", "/api/v1/listings", d)) as Listing;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Finding regions by place name, offline.
|
||||
//
|
||||
// A region is a 3-character geohash cell, about 150 km wide: right for the
|
||||
// network, meaningless to a person. This turns "Bonn" or "Cologne" into the
|
||||
// cell(s) to follow, using a list of cities shipped with the page
|
||||
// (places.tsv, GeoNames, CC-BY 4.0; see scripts/places.mjs). Nothing about what
|
||||
// a person looks for leaves the device.
|
||||
|
||||
import { encodeGeohash } from "./geohash.ts";
|
||||
|
||||
export interface Place {
|
||||
name: string;
|
||||
lat: number;
|
||||
lon: number;
|
||||
/** ISO country code. */
|
||||
cc: string;
|
||||
population: number;
|
||||
/** Other names people use (Köln: Cologne). */
|
||||
alts: string[];
|
||||
/** Folded search keys for the name and every alternative, in that order. */
|
||||
keys: string[];
|
||||
}
|
||||
|
||||
export interface Match {
|
||||
place: Place;
|
||||
/** The name that matched, when it is not the place's main name. */
|
||||
matched: string | null;
|
||||
}
|
||||
|
||||
/** Lower case, no diacritics, ß as ss: "Zürich", "zurich" and "ZÜRICH" are one key. */
|
||||
export function fold(s: string): string {
|
||||
return s.normalize("NFD").replace(/\p{M}/gu, "").replace(/ß/g, "ss").toLowerCase();
|
||||
}
|
||||
|
||||
/** How a German keyboard without umlauts writes them: "muenchen" → "munchen". */
|
||||
function unTranslit(s: string): string {
|
||||
return s.replace(/ae/g, "a").replace(/oe/g, "o").replace(/ue/g, "u");
|
||||
}
|
||||
|
||||
/** Reads places.tsv: name, ASCII name, lat, lon, country, population, alternatives. */
|
||||
export function parsePlaces(tsv: string): Place[] {
|
||||
const out: Place[] = [];
|
||||
for (const line of tsv.split("\n")) {
|
||||
if (!line) continue;
|
||||
const [name, ascii, lat, lon, cc, pop, alt] = line.split("\t");
|
||||
if (!name || lat === undefined || lon === undefined) continue;
|
||||
const alts = alt ? alt.split("|") : [];
|
||||
const keys = [name, ...alts].map(fold);
|
||||
if (ascii) keys.push(fold(ascii)); // "Koeln": searchable, but shown as "Köln"
|
||||
out.push({ name, lat: Number(lat), lon: Number(lon), cc: cc ?? "", population: Number(pop) || 0, alts, keys });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function score(key: string, q: string): number {
|
||||
if (key === q) return 0;
|
||||
if (key.startsWith(q)) return 1;
|
||||
if (key.split(/[\s-]+/).some((w) => w.startsWith(q))) return 2;
|
||||
return q.length >= 3 && key.includes(q) ? 3 : 4;
|
||||
}
|
||||
|
||||
/** The best matches for what the person typed: exact names first, then by size. */
|
||||
export function searchPlaces(places: Place[], query: string, limit = 8): Match[] {
|
||||
const q1 = fold(query.trim());
|
||||
if (q1.length < 2) return [];
|
||||
const qs = [...new Set([q1, unTranslit(q1)])];
|
||||
const hits: { m: Match; s: number }[] = [];
|
||||
for (const p of places) {
|
||||
let best = 4;
|
||||
let bestKey = 0;
|
||||
for (let i = 0; i < p.keys.length; i++) {
|
||||
for (const q of qs) {
|
||||
const s = score(p.keys[i]!, q);
|
||||
if (s < best) [best, bestKey] = [s, i];
|
||||
}
|
||||
}
|
||||
if (best < 4) {
|
||||
// Indexes past the alternatives are the ASCII spelling of the main name.
|
||||
const matched = bestKey >= 1 && bestKey <= p.alts.length ? p.alts[bestKey - 1]! : null;
|
||||
hits.push({ m: { place: p, matched }, s: best });
|
||||
}
|
||||
}
|
||||
hits.sort((a, b) => a.s - b.s || b.m.place.population - a.m.place.population);
|
||||
return hits.slice(0, limit).map((h) => h.m);
|
||||
}
|
||||
|
||||
const KM_PER_DEGREE = 111.2;
|
||||
|
||||
/**
|
||||
* The cells to follow for a place: the one it lies in, then any other cell
|
||||
* within about `km` of it, so a city near a cell's edge does not miss the
|
||||
* listings just across it. The place's own cell comes first.
|
||||
*/
|
||||
export function cellsNear(lat: number, lon: number, km = 40): string[] {
|
||||
const cell = (la: number, lo: number) =>
|
||||
encodeGeohash(Math.max(-89.999, Math.min(89.999, la)), ((((lo + 180) % 360) + 360) % 360) - 180, 3);
|
||||
const out = [cell(lat, lon)];
|
||||
const dLat = 1 / KM_PER_DEGREE;
|
||||
const dLon = 1 / (KM_PER_DEGREE * Math.max(0.05, Math.cos((lat * Math.PI) / 180)));
|
||||
// Two rings (half and full distance) in 16 directions: a cell clipping the
|
||||
// circle anywhere is hit by one of them.
|
||||
for (const r of [km / 2, km]) {
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const a = (i / 16) * 2 * Math.PI;
|
||||
const c = cell(lat + Math.sin(a) * r * dLat, lon + Math.cos(a) * r * dLon);
|
||||
if (!out.includes(c)) out.push(c);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The largest known place of each cell, to label a code with a name a person knows. */
|
||||
export function biggestPlaceByCell(places: Place[]): Map<string, Place> {
|
||||
const by = new Map<string, Place>();
|
||||
for (const p of places) {
|
||||
const c = encodeGeohash(p.lat, p.lon, 3);
|
||||
const cur = by.get(c);
|
||||
if (!cur || p.population > cur.population) by.set(c, p);
|
||||
}
|
||||
return by;
|
||||
}
|
||||
|
||||
let loaded: Promise<Place[]> | null = null;
|
||||
|
||||
/** Fetches places.tsv once. Failing is not fatal: region codes can still be typed. */
|
||||
export function loadPlaces(): Promise<Place[]> {
|
||||
loaded ??= fetch("places.tsv")
|
||||
.then((r) => {
|
||||
if (!r.ok) throw new Error(`${r.status}`);
|
||||
return r.text();
|
||||
})
|
||||
.then(parsePlaces)
|
||||
.catch((e) => {
|
||||
loaded = null; // try again next time
|
||||
throw e;
|
||||
});
|
||||
return loaded;
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
// Choosing the regions a node follows, by place name.
|
||||
//
|
||||
// The owner's "Regions" page. A person searches a place ("Bonn", "Cologne"),
|
||||
// sees the cells around it (the one it lies in and any within about 40 km),
|
||||
// unticks what they do not want, and adds them. Region codes can still be
|
||||
// typed for those who know them. Saving changes what the node follows at once.
|
||||
|
||||
import { append, clear, h } from "./dom.ts";
|
||||
import { lang, t } from "./i18n.ts";
|
||||
import { Unauthorized, getToken, setRegions } from "./ownerApi.ts";
|
||||
import { biggestPlaceByCell, cellsNear, loadPlaces, searchPlaces, type Match, type Place } from "./places.ts";
|
||||
import { state } from "./state.ts";
|
||||
|
||||
const CODE = /^[0-9bcdefghjkmnpqrstuvwxyz]{3}$/;
|
||||
const MAX_REGIONS = 20;
|
||||
|
||||
function countryName(cc: string): string {
|
||||
try {
|
||||
return new Intl.DisplayNames([lang], { type: "region" }).of(cc) ?? cc;
|
||||
} catch {
|
||||
return cc;
|
||||
}
|
||||
}
|
||||
|
||||
function errText(e: unknown): string {
|
||||
if (e instanceof Unauthorized) return t("reg.signedOut");
|
||||
if (e && typeof e === "object" && "message" in e) return String((e as { message: unknown }).message);
|
||||
return typeof e === "string" ? e : t("reg.failed");
|
||||
}
|
||||
|
||||
export interface PickerOptions {
|
||||
/** Regions already followed. */
|
||||
initial: string[];
|
||||
submitLabel: string;
|
||||
/** Saves the choice; a rejection is shown to the person and they can try again. */
|
||||
onSubmit: (regions: string[]) => Promise<void>;
|
||||
}
|
||||
|
||||
/** The whole picker: search, chosen regions, code entry and a save button. */
|
||||
export function regionPicker(opts: PickerOptions): HTMLElement {
|
||||
const chosen: string[] = [...opts.initial];
|
||||
let places: Place[] = [];
|
||||
let biggest = new Map<string, Place>();
|
||||
|
||||
const label = (code: string): string => {
|
||||
const p = biggest.get(code);
|
||||
return p ? `${code} · ${p.name}` : code;
|
||||
};
|
||||
|
||||
const chips = h("ul", { class: "rp-chips", "aria-label": t("reg.chosen") });
|
||||
const drawChips = () => {
|
||||
clear(chips);
|
||||
if (chosen.length === 0) append(chips, [h("li", { class: "muted" }, t("reg.nothing"))]);
|
||||
for (const code of chosen) {
|
||||
append(chips, [
|
||||
h(
|
||||
"li",
|
||||
{ class: "rp-chip" },
|
||||
h("span", null, label(code)),
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
class: "rp-chip-x",
|
||||
"aria-label": t("reg.remove", { region: label(code) }),
|
||||
onclick: () => {
|
||||
chosen.splice(chosen.indexOf(code), 1);
|
||||
drawChips();
|
||||
},
|
||||
},
|
||||
"×",
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
};
|
||||
|
||||
// --- search ---
|
||||
const results = h("ul", { class: "rp-results", role: "listbox", "aria-label": t("reg.results") });
|
||||
const cellsBox = h("div", { class: "rp-cells" });
|
||||
const hint = h("p", { class: "muted small", "aria-live": "polite" });
|
||||
|
||||
const showCells = (place: Place) => {
|
||||
clear(cellsBox);
|
||||
clear(results);
|
||||
const cells = cellsNear(place.lat, place.lon);
|
||||
const boxes = cells.map((code, i) => {
|
||||
const box = h("input", { type: "checkbox", name: `cell-${code}`, checked: true, "aria-label": code });
|
||||
return { code, box, row: h("label", { class: "rp-cell" }, box, h("span", null, `${label(code)}${i === 0 ? ` (${t("reg.here")})` : ""}`)) };
|
||||
});
|
||||
append(cellsBox, [
|
||||
h("h2", null, t("reg.cellsTitle", { place: place.name })),
|
||||
h("p", { class: "muted small" }, t("reg.cellsHelp")),
|
||||
...boxes.map((b) => b.row),
|
||||
h(
|
||||
"div",
|
||||
{ class: "actions" },
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
class: "btn",
|
||||
onclick: () => {
|
||||
for (const b of boxes) if (b.box.checked && !chosen.includes(b.code)) chosen.push(b.code);
|
||||
clear(cellsBox);
|
||||
search.value = "";
|
||||
drawChips();
|
||||
},
|
||||
},
|
||||
t("reg.add"),
|
||||
),
|
||||
),
|
||||
]);
|
||||
};
|
||||
|
||||
const showMatches = (matches: Match[]) => {
|
||||
clear(results);
|
||||
for (const m of matches) {
|
||||
const p = m.place;
|
||||
append(results, [
|
||||
h(
|
||||
"li",
|
||||
{ role: "option" },
|
||||
h(
|
||||
"button",
|
||||
{ type: "button", class: "rp-result", onclick: () => showCells(p) },
|
||||
h("strong", null, p.name),
|
||||
m.matched ? ` (${m.matched})` : "",
|
||||
h("span", { class: "muted" }, ` · ${countryName(p.cc)}`),
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
};
|
||||
|
||||
const search = h("input", {
|
||||
type: "search",
|
||||
name: "place",
|
||||
autocomplete: "off",
|
||||
spellcheck: "false",
|
||||
placeholder: t("reg.placeholder"),
|
||||
"aria-label": t("reg.search"),
|
||||
disabled: true, // until the list of places has loaded: an early search would find nothing
|
||||
});
|
||||
search.addEventListener("input", () => {
|
||||
clear(cellsBox);
|
||||
const q = search.value;
|
||||
if (q.trim().length < 2) {
|
||||
clear(results);
|
||||
hint.textContent = "";
|
||||
return;
|
||||
}
|
||||
const found = searchPlaces(places, q);
|
||||
showMatches(found);
|
||||
hint.textContent = found.length === 0 ? t("reg.none") : "";
|
||||
});
|
||||
|
||||
void loadPlaces().then(
|
||||
(p) => {
|
||||
places = p;
|
||||
biggest = biggestPlaceByCell(p);
|
||||
search.disabled = false;
|
||||
drawChips(); // names for the codes already chosen
|
||||
},
|
||||
() => {
|
||||
hint.textContent = t("reg.noPlaces");
|
||||
},
|
||||
);
|
||||
|
||||
// --- codes and saving ---
|
||||
const codes = h("input", { type: "text", name: "regions", placeholder: "u1j", autocomplete: "off", spellcheck: "false", "aria-label": t("reg.codes") });
|
||||
const problem = h("p", { class: "error", role: "alert" });
|
||||
const go = h("button", { type: "submit", class: "btn primary" }, opts.submitLabel);
|
||||
|
||||
const form = h(
|
||||
"form",
|
||||
{
|
||||
class: "stack regions",
|
||||
onsubmit: (ev) => {
|
||||
ev.preventDefault();
|
||||
problem.textContent = "";
|
||||
for (const raw of codes.value.split(/[\s,;]+/).filter(Boolean)) {
|
||||
const code = raw.toLowerCase();
|
||||
if (!CODE.test(code)) {
|
||||
problem.textContent = t("reg.badCode", { code: raw });
|
||||
return;
|
||||
}
|
||||
if (!chosen.includes(code)) chosen.push(code);
|
||||
}
|
||||
codes.value = "";
|
||||
drawChips();
|
||||
if (chosen.length === 0) {
|
||||
problem.textContent = t("reg.needOne");
|
||||
return;
|
||||
}
|
||||
if (chosen.length > MAX_REGIONS) {
|
||||
problem.textContent = t("reg.tooMany", { max: MAX_REGIONS });
|
||||
return;
|
||||
}
|
||||
go.disabled = true;
|
||||
const label = go.textContent;
|
||||
go.textContent = t("reg.saving");
|
||||
opts.onSubmit([...chosen]).catch((e) => {
|
||||
problem.textContent = errText(e);
|
||||
go.disabled = false;
|
||||
go.textContent = label;
|
||||
});
|
||||
},
|
||||
},
|
||||
h("label", null, t("reg.search"), search),
|
||||
hint,
|
||||
results,
|
||||
cellsBox,
|
||||
h("h2", null, t("reg.chosen")),
|
||||
chips,
|
||||
h("label", null, t("reg.codes"), codes),
|
||||
h("p", { class: "muted small" }, t("reg.codesHelp")),
|
||||
problem,
|
||||
h("div", { class: "actions" }, go),
|
||||
h("p", { class: "muted small" }, t("reg.credit")),
|
||||
);
|
||||
drawChips();
|
||||
return form;
|
||||
}
|
||||
|
||||
/** The owner's "Regions" page: shows what the node follows and changes it. */
|
||||
export function showRegions(message = ""): void {
|
||||
const root = document.getElementById("app")!;
|
||||
document.body.classList.remove("wide");
|
||||
clear(root);
|
||||
if (!getToken()) {
|
||||
location.hash = "#/mine"; // the sign-in form
|
||||
return;
|
||||
}
|
||||
const picker = regionPicker({
|
||||
initial: state.node?.regions ?? [],
|
||||
submitLabel: t("reg.save"),
|
||||
onSubmit: async (regions) => {
|
||||
const now = await setRegions(regions);
|
||||
if (state.node) state.node.regions = now;
|
||||
const statusEl = document.getElementById("status");
|
||||
if (statusEl && state.node) {
|
||||
statusEl.textContent = t("status.line", { listings: state.node.listings, peers: state.node.peers, regions: now.join(", ") });
|
||||
}
|
||||
showRegions(t("reg.saved")); // the page again, showing what is followed now
|
||||
},
|
||||
});
|
||||
append(root, [
|
||||
h(
|
||||
"section",
|
||||
{ class: "panel" },
|
||||
h("h1", null, t("reg.title")),
|
||||
h("p", { class: "muted" }, t("reg.intro")),
|
||||
h("p", { class: "ok", role: "status" }, message),
|
||||
picker,
|
||||
),
|
||||
]);
|
||||
}
|
||||
+34247
File diff suppressed because it is too large
Load Diff
@@ -269,6 +269,16 @@ label.check { flex-direction: row; align-items: center; gap: 8px; }
|
||||
.badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||
.badge.warn { color: var(--warn); background: var(--warn-bg); }
|
||||
.badge.muted { color: var(--muted); background: transparent; border: 1px solid var(--line); }
|
||||
/* the region picker */
|
||||
.rp-chips, .rp-results { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.rp-results { flex-direction: column; flex-wrap: nowrap; }
|
||||
.rp-chip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 4px 2px 10px; background: var(--bg); border: 1px solid var(--line); border-radius: 999px; }
|
||||
.rp-chip-x { border: 0; background: none; cursor: pointer; font-size: 1.1rem; line-height: 1; padding: 2px 8px; color: inherit; }
|
||||
.rp-result { width: 100%; text-align: left; background: none; border: 1px solid transparent; border-radius: 6px; padding: 8px; cursor: pointer; color: inherit; font: inherit; }
|
||||
.rp-result:hover, .rp-result:focus-visible { border-color: var(--line); background: var(--bg); }
|
||||
.rp-cells { display: grid; gap: 6px; }
|
||||
.stack label.rp-cell { flex-direction: row; align-items: center; gap: 8px; color: inherit; font-size: 1rem; }
|
||||
p.ok { color: var(--ok); }
|
||||
.chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
|
||||
.chip {
|
||||
min-height: 2.25rem;
|
||||
|
||||
+6
-1
@@ -211,9 +211,14 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
|
||||
res.writeHead(code, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(body));
|
||||
};
|
||||
if (url.pathname === "/places.tsv") {
|
||||
// A static file of the UI, as the real node serves it.
|
||||
res.writeHead(200, { "Content-Type": "text/tab-separated-values" });
|
||||
return void res.end(readFileSync(new URL("../static/places.tsv", import.meta.url)));
|
||||
}
|
||||
// The owner's token-protected routes are played by the test, if it sets `owner`.
|
||||
const writesListing = req.method !== "GET" && /^\/api\/v1\/listings(\/[0-9a-f]{32})?$/.test(url.pathname);
|
||||
if (writesListing || /^\/api\/v1\/(mine|inbox)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
|
||||
if (writesListing || /^\/api\/v1\/(mine|inbox|regions)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
|
||||
let body = "";
|
||||
req.on("data", (c) => (body += c));
|
||||
req.on("end", () => {
|
||||
|
||||
@@ -41,6 +41,11 @@ function fakeNode() {
|
||||
s.calls.push({ method: r.method, path: r.path + (r.query.size ? "?" + r.query : ""), body: r.body, auth: r.auth });
|
||||
if (r.auth !== `Bearer ${s.token}`) return { status: 401, body: { error: "unauthorized" } };
|
||||
if (r.path === "/api/v1/mine") return { status: 200, body: s.mine };
|
||||
if (r.path === "/api/v1/regions" && r.method === "PUT") {
|
||||
const { regions } = JSON.parse(r.body) as { regions: string[] };
|
||||
if (regions.includes("zzz")) return { status: 400, body: { error: `"zzz" is not a region: use 3 geohash characters` } };
|
||||
return { status: 200, body: { regions } };
|
||||
}
|
||||
if (r.path === "/api/v1/inbox") return { status: 200, body: s.threads.filter((t) => t.listing === r.query.get("listing")) };
|
||||
const th = /^\/api\/v1\/inbox\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(r.path);
|
||||
if (th) {
|
||||
@@ -383,3 +388,52 @@ test("signing out forgets the token", async () => {
|
||||
assert.equal(page!.window.sessionStorage.getItem("allmende.owner.token"), null);
|
||||
await page!.waitFor(() => q("nav a[href='#/mine']") === null, "the owner link to vanish");
|
||||
});
|
||||
|
||||
test("the owner picks regions by place name and the node follows them at once", async () => {
|
||||
open(`#/login/${TOKEN}`);
|
||||
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
|
||||
qa(".pane-listings a").find((a) => a.textContent === "Regions")!.click();
|
||||
await page!.waitFor(() => q('[name="place"]') !== null, "the regions page");
|
||||
assert.ok(q(".rp-chips")!.textContent!.includes("u1x"), "what the node follows now");
|
||||
const search = q<HTMLInputElement>('[name="place"]')!;
|
||||
await page!.waitFor(() => !search.disabled, "the place list is loaded");
|
||||
|
||||
search.value = "köln";
|
||||
search.dispatchEvent(new page!.window.Event("input", { bubbles: true }));
|
||||
await page!.waitFor(() => q(".rp-result") !== null, "a result");
|
||||
q(".rp-result")!.click();
|
||||
await page!.waitFor(() => /Regions around/.test(text()), "the cells around it");
|
||||
button("Add")!.click();
|
||||
assert.ok(qa(".rp-chip").length >= 2, "the new regions are added next to the old one");
|
||||
|
||||
submit(q("form")!);
|
||||
await page!.waitFor(() => /Saved/.test(text()), "saved");
|
||||
const put = node.s.calls.find((c) => c.method === "PUT" && c.path === "/api/v1/regions")!;
|
||||
assert.equal(put.auth, `Bearer ${TOKEN}`, "only the owner can change regions");
|
||||
const sent = (JSON.parse(put.body) as { regions: string[] }).regions;
|
||||
assert.equal(sent[0], "u1x");
|
||||
assert.ok(sent.includes("u1j"), `Köln's own cell is followed: ${sent}`);
|
||||
assert.ok(q("#status")!.textContent!.includes(sent.join(", ")), "the status line shows the new regions");
|
||||
});
|
||||
|
||||
test("a region the node refuses is explained and the page stays usable", async () => {
|
||||
open(`#/login/${TOKEN}`);
|
||||
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
|
||||
location_(`#/mine/regions`);
|
||||
await page!.waitFor(() => q('[name="regions"]') !== null, "the regions page");
|
||||
q<HTMLInputElement>('[name="regions"]')!.value = "zzz";
|
||||
submit(q("form")!);
|
||||
await page!.waitFor(() => /not a region/.test(text()), "the node's explanation");
|
||||
assert.ok(!button("Save")?.disabled, "saving can be tried again");
|
||||
});
|
||||
|
||||
test("without signing in the regions page leads to the sign-in", async () => {
|
||||
open("#/mine/regions");
|
||||
await page!.waitFor(() => q('input[name="token"]') !== null, "the sign-in form");
|
||||
assert.equal(node.s.calls.length, 0);
|
||||
});
|
||||
|
||||
/** Moves the open page to another hash, as a click on a link would. */
|
||||
function location_(hash: string): void {
|
||||
page!.window.location.hash = hash;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { decodeGeohash, encodeGeohash } from "../src/geohash.ts";
|
||||
import { biggestPlaceByCell, cellsNear, fold, parsePlaces, searchPlaces } from "../src/places.ts";
|
||||
|
||||
// The real list the app ships.
|
||||
const places = parsePlaces(readFileSync(new URL("../static/places.tsv", import.meta.url), "utf8"));
|
||||
const first = (q: string) => searchPlaces(places, q, 1)[0];
|
||||
|
||||
test("the list is worldwide and big enough", () => {
|
||||
assert.ok(places.length > 30_000);
|
||||
});
|
||||
|
||||
test("names are found however they are spelled", () => {
|
||||
assert.equal(first("Bonn")?.place.name, "Bonn");
|
||||
assert.equal(first("bonn")?.place.name, "Bonn");
|
||||
assert.equal(first("köln")?.place.name, "Köln");
|
||||
assert.equal(first("koeln")?.place.name, "Köln");
|
||||
assert.equal(first("KOELN")?.place.name, "Köln");
|
||||
assert.equal(first("zurich")?.place.name, "Zürich");
|
||||
assert.equal(first("Zürich")?.place.name, "Zürich");
|
||||
assert.equal(first("Frankfurt am Main")?.place.cc, "DE");
|
||||
});
|
||||
|
||||
test("other languages' names lead to the place, and say what matched", () => {
|
||||
const c = first("cologne");
|
||||
assert.equal(c?.place.name, "Köln");
|
||||
assert.equal(c?.matched, "Cologne");
|
||||
assert.equal(first("münchen")?.place.cc, "DE", "Munich, found by its German name");
|
||||
assert.equal(first("muenchen")?.place.cc, "DE");
|
||||
assert.equal(first("nuernberg")?.place.cc, "DE");
|
||||
assert.equal(first("prag")?.place.cc, "CZ");
|
||||
assert.equal(first("wien")?.place.cc, "AT");
|
||||
assert.equal(first("Köln")?.matched, null, "the main name is not repeated");
|
||||
});
|
||||
|
||||
test("the big city wins over a small namesake, and prefixes work", () => {
|
||||
const vienna = searchPlaces(places, "vienna", 5);
|
||||
assert.equal(vienna[0]!.place.cc, "AT");
|
||||
assert.ok(vienna.some((m) => m.place.cc === "US"), "the others are still offered");
|
||||
const ham = searchPlaces(places, "ham", 8).map((m) => m.place.name);
|
||||
assert.ok(ham.includes("Hamburg") || ham.includes("Hamm"), ham.join());
|
||||
assert.deepEqual(searchPlaces(places, "b"), [], "one letter is too little to search");
|
||||
assert.deepEqual(searchPlaces(places, "qqqzzzxxx"), []);
|
||||
assert.deepEqual(searchPlaces(places, " "), []);
|
||||
});
|
||||
|
||||
test("folding ignores case, accents and ß", () => {
|
||||
assert.equal(fold("Zürich"), "zurich");
|
||||
assert.equal(fold("Straße"), "strasse");
|
||||
assert.equal(fold("ÅRHUS"), "arhus");
|
||||
});
|
||||
|
||||
test("a place gives the cell it lies in first", () => {
|
||||
const bonn = first("Bonn")!.place;
|
||||
const cells = cellsNear(bonn.lat, bonn.lon);
|
||||
assert.equal(cells[0], encodeGeohash(bonn.lat, bonn.lon, 3));
|
||||
assert.equal(cells[0], "u1j", "Bonn, the project's default region");
|
||||
assert.equal(new Set(cells).size, cells.length);
|
||||
assert.ok(cells.every((c) => /^[0-9bcdefghjkmnpqrstuvwxyz]{3}$/.test(c)));
|
||||
});
|
||||
|
||||
test("only a place near a cell's edge brings in its neighbour", () => {
|
||||
const cell = decodeGeohash("u1j")!;
|
||||
// The middle of the cell is far from every edge.
|
||||
assert.deepEqual(cellsNear(cell.lat, cell.lon), ["u1j"]);
|
||||
// 10 km inside the east edge: the next cell east is within reach.
|
||||
const kmPerLon = 111.2 * Math.cos((cell.lat * Math.PI) / 180);
|
||||
const nearEast = cellsNear(cell.lat, cell.lon + cell.lonErr - 10 / kmPerLon);
|
||||
assert.equal(nearEast[0], "u1j");
|
||||
assert.ok(nearEast.length >= 2, "the eastern neighbour");
|
||||
// At this latitude a cell is only about 100 km wide, so its middle is 50 km
|
||||
// from the edges: out of a 40 km reach, inside an 80 km one.
|
||||
assert.ok(cell.lonErr * kmPerLon > 45 && cell.lonErr * kmPerLon < 55);
|
||||
assert.ok(cellsNear(cell.lat, cell.lon, 80).length >= 2, "the reach is a parameter");
|
||||
});
|
||||
|
||||
test("places at the edge of the map still give valid cells", () => {
|
||||
for (const [lat, lon] of [[89.99, 0], [-89.99, 10], [0, 179.99], [0, -179.99], [64.1, -21.9]] as const) {
|
||||
const cells = cellsNear(lat, lon);
|
||||
assert.ok(cells.length >= 1 && cells.every((c) => c.length === 3), `${lat},${lon}: ${cells}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("a cell is named after the biggest place in it", () => {
|
||||
const byCell = biggestPlaceByCell(places);
|
||||
const bonn = first("Bonn")!.place;
|
||||
const named = byCell.get("u1j")!;
|
||||
assert.ok(named.population >= bonn.population, `${named.name} is at least as big as Bonn`);
|
||||
assert.equal(byCell.get("000"), undefined, "an empty cell (open ocean) has no name");
|
||||
});
|
||||
Reference in New Issue
Block a user