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:
2026-11-18 10:28:16 +01:00
co-authored by Claude Sonnet 5.5
parent e7bec4fb63
commit fd439710df
24 changed files with 70080 additions and 42 deletions
+258
View File
@@ -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,
),
]);
}