A listing page says when the node hides the listing and who flagged it. A visitor can tip off the operator (proof-of-work, nothing is hidden by it); the signed-in operator can sign or withdraw a report from the page and works through the tips at #/mine/reports. e2e covers the real binaries. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
405 lines
14 KiB
TypeScript
405 lines
14 KiB
TypeScript
import { getListing, getStatus, search } from "./api.ts";
|
|
import { append, clear, h } from "./dom.ts";
|
|
import { date, price, rooms, shortKey, statusLine } from "./format.ts";
|
|
import { decodeGeohash } from "./geohash.ts";
|
|
import { lang, t, type Key } from "./i18n.ts";
|
|
import { contactPanel, showConversation, showInbox } from "./chat.ts";
|
|
import { showOwner } from "./owner.ts";
|
|
import { reportPanel, showReports } from "./reports.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";
|
|
|
|
const PAGE = 20;
|
|
const GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
|
|
|
|
const app = document.getElementById("app")!;
|
|
const statusEl = document.getElementById("status")!;
|
|
|
|
// --- helpers --------------------------------------------------------------
|
|
|
|
/** Translates a value from a listing if it is a known one; unknown values are shown as plain text. */
|
|
function label(prefix: "kind" | "cat", value: string | undefined): string {
|
|
if (!value) return "";
|
|
const key = `${prefix}.${value}` as Key;
|
|
const known = ["kind.rent", "kind.sale", "cat.apartment", "cat.house", "cat.room", "cat.commercial"];
|
|
return known.includes(key) ? t(key) : value;
|
|
}
|
|
|
|
function where(geohash: string): string {
|
|
const a = decodeGeohash(geohash);
|
|
if (!a) return geohash;
|
|
const ns = a.lat >= 0 ? "N" : "S";
|
|
const ew = a.lon >= 0 ? (lang === "de" ? "O" : "E") : lang === "de" ? "W" : "W";
|
|
return `${Math.abs(a.lat).toFixed(2)}° ${ns}, ${Math.abs(a.lon).toFixed(2)}° ${ew}`;
|
|
}
|
|
|
|
function badge(ok: boolean): HTMLElement {
|
|
return h("span", { class: ok ? "badge ok" : "badge bad" }, (ok ? "✓ " : "✗ ") + t(ok ? "badge.ok" : "badge.bad"));
|
|
}
|
|
|
|
function num(v: string | null): number {
|
|
const n = Number((v ?? "").replace(",", "."));
|
|
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
}
|
|
|
|
/** Converts the human-friendly URL parameters into the API's units. */
|
|
function toApi(p: URLSearchParams): URLSearchParams {
|
|
const q = new URLSearchParams();
|
|
for (const k of ["kind", "category", "geohash"]) {
|
|
const v = p.get(k)?.trim().toLowerCase();
|
|
if (v) q.set(k, v);
|
|
}
|
|
const eur = num(p.get("max_price"));
|
|
if (eur) q.set("max_price", String(Math.round(eur * 100)));
|
|
const area = num(p.get("min_area"));
|
|
if (area) q.set("min_area", String(Math.ceil(area)));
|
|
const r = num(p.get("min_rooms"));
|
|
if (r) q.set("min_rooms", String(Math.ceil(r * 2)));
|
|
return q;
|
|
}
|
|
|
|
// --- search view ----------------------------------------------------------
|
|
|
|
function field(text: string, input: HTMLElement, hint?: string): HTMLElement {
|
|
return h("label", { class: "field" }, h("span", { class: "field-label" }, text), input, hint && h("span", { class: "hint" }, hint));
|
|
}
|
|
|
|
function select(name: string, current: string, options: [string, string][]): HTMLSelectElement {
|
|
const el = h("select", { name });
|
|
for (const [value, text] of options) {
|
|
el.append(h("option", { value, selected: value === current }, text));
|
|
}
|
|
return el;
|
|
}
|
|
|
|
function searchForm(params: URLSearchParams): HTMLFormElement {
|
|
const get = (k: string) => params.get(k) ?? "";
|
|
const regions = h("datalist", { id: "regions" }, ...(state.node?.regions ?? []).map((r) => h("option", { value: r })));
|
|
const form = h(
|
|
"form",
|
|
{ class: "filters" },
|
|
field(t("filter.kind"), select("kind", get("kind"), [["", t("filter.any")], ["rent", t("kind.rent")], ["sale", t("kind.sale")]])),
|
|
field(
|
|
t("filter.category"),
|
|
select("category", get("category"), [
|
|
["", t("filter.any")],
|
|
["apartment", t("cat.apartment")],
|
|
["house", t("cat.house")],
|
|
["room", t("cat.room")],
|
|
["commercial", t("cat.commercial")],
|
|
]),
|
|
),
|
|
field(
|
|
t("filter.region"),
|
|
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: state.node?.regions[0] ?? "u1x" }),
|
|
t("filter.regionHint"),
|
|
),
|
|
field(t("filter.maxPrice"), h("input", { name: "max_price", type: "number", min: 0, step: 50, inputmode: "decimal", value: get("max_price") })),
|
|
field(t("filter.minArea"), h("input", { name: "min_area", type: "number", min: 0, step: 5, value: get("min_area") })),
|
|
field(t("filter.minRooms"), h("input", { name: "min_rooms", type: "number", min: 0, step: 0.5, value: get("min_rooms") })),
|
|
h(
|
|
"div",
|
|
{ class: "actions" },
|
|
h("button", { type: "submit", class: "btn primary" }, t("filter.search")),
|
|
h("button", { type: "button", class: "btn", onclick: () => navigate("#/") }, t("filter.reset")),
|
|
),
|
|
regions,
|
|
);
|
|
form.addEventListener("submit", (e) => {
|
|
e.preventDefault();
|
|
const q = new URLSearchParams();
|
|
for (const [k, v] of new FormData(form)) {
|
|
if (typeof v === "string" && v.trim() !== "") q.set(k, v.trim());
|
|
}
|
|
const s = q.toString();
|
|
navigate(s ? `#/?${s}` : "#/");
|
|
});
|
|
return form;
|
|
}
|
|
|
|
function navigate(hash: string): void {
|
|
if (location.hash === hash || (hash === "#/" && location.hash === "")) route();
|
|
else location.hash = hash;
|
|
}
|
|
|
|
function card(l: Listing): HTMLElement {
|
|
const facts = [
|
|
label("cat", l.category),
|
|
l.area_m2 ? t("card.area", { n: l.area_m2 }) : "",
|
|
l.rooms_x2 ? rooms(l.rooms_x2) : "",
|
|
].filter(Boolean);
|
|
return h(
|
|
"a",
|
|
{ class: "card", href: `#/l/${l.author}/${l.id}` }, // author and id were verified to be hex
|
|
h("div", { class: "card-top" }, h("h3", null, l.title ?? ""), badge(true)),
|
|
h("p", { class: "price" }, price(l)),
|
|
h("p", { class: "facts" }, facts.join(" · ")),
|
|
h("p", { class: "muted" }, where(l.geohash)),
|
|
);
|
|
}
|
|
|
|
async function loadResults(gen: number, q: URLSearchParams, root: HTMLElement): Promise<void> {
|
|
const cards = h("div", { class: "cards" });
|
|
const foot = h("div", { class: "results-foot" });
|
|
append(root, [cards, foot]);
|
|
let offset = 0;
|
|
let shown = 0;
|
|
let hidden = 0;
|
|
|
|
const more = async (): Promise<void> => {
|
|
clear(foot);
|
|
foot.append(h("p", { class: "muted" }, t("results.loading")));
|
|
let items: unknown[];
|
|
try {
|
|
const paged = new URLSearchParams(q);
|
|
paged.set("limit", String(PAGE));
|
|
paged.set("offset", String(offset));
|
|
items = await search(paged);
|
|
} catch {
|
|
if (gen !== state.generation) return;
|
|
clear(foot);
|
|
foot.append(h("p", { class: "error" }, t("results.error")));
|
|
return;
|
|
}
|
|
if (gen !== state.generation) return;
|
|
|
|
const opts = verifyOpts();
|
|
for (const raw of items) {
|
|
const verdict = verifyListing(raw, opts);
|
|
if (verdict.ok) {
|
|
cards.append(card(raw as Listing));
|
|
shown++;
|
|
} else {
|
|
hidden++;
|
|
}
|
|
}
|
|
offset += items.length;
|
|
|
|
clear(foot);
|
|
if (hidden > 0) foot.append(h("p", { class: "warn" }, t("results.hidden", { n: hidden })));
|
|
if (shown === 0 && items.length < PAGE) foot.append(h("p", { class: "muted" }, t("results.none")));
|
|
if (items.length === PAGE) {
|
|
foot.append(h("button", { type: "button", class: "btn", onclick: () => void more() }, t("results.more")));
|
|
}
|
|
};
|
|
await more();
|
|
}
|
|
|
|
function showSearch(params: URLSearchParams): void {
|
|
const gen = state.generation;
|
|
clear(app);
|
|
const results = h("div", { class: "results", "aria-live": "polite" });
|
|
app.append(h("p", { class: "tagline" }, t("app.tagline")));
|
|
if (state.node && state.node.regions.length === 0) {
|
|
app.append(
|
|
h(
|
|
"p",
|
|
{ class: "notice", role: "status" },
|
|
t("search.noRegions"),
|
|
" ",
|
|
getToken() ? h("a", { href: "#/mine/regions" }, t("search.chooseRegions")) : null,
|
|
),
|
|
);
|
|
}
|
|
app.append(searchForm(params), results);
|
|
|
|
const prefix = params.get("geohash")?.trim().toLowerCase();
|
|
if (prefix && !GEOHASH_PREFIX.test(prefix)) {
|
|
results.append(h("p", { class: "error" }, t("filter.regionHint")));
|
|
return;
|
|
}
|
|
void loadResults(gen, toApi(params), results);
|
|
}
|
|
|
|
// --- detail view ----------------------------------------------------------
|
|
|
|
function checkList(v: Verdict): HTMLElement {
|
|
return h(
|
|
"ul",
|
|
{ class: "checks" },
|
|
...v.checks.map((c) =>
|
|
h(
|
|
"li",
|
|
{ class: c.ok ? "ok" : "bad" },
|
|
h("span", { class: "mark", "aria-hidden": "true" }, c.ok ? "✓" : "✗"),
|
|
h("span", null, t(`verify.${c.id}` as Key)),
|
|
c.info && h("span", { class: "muted info" }, c.info),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
function verification(raw: unknown, l: Listing, v: Verdict): HTMLElement {
|
|
return h(
|
|
"section",
|
|
{ class: "panel" },
|
|
h("h2", null, t("verify.title")),
|
|
h("p", { class: "muted" }, t("verify.intro")),
|
|
checkList(v),
|
|
v.ok &&
|
|
h(
|
|
"dl",
|
|
{ class: "kv" },
|
|
h("dt", null, t("verify.owner")),
|
|
h("dd", { class: "mono" }, shortKey(l.author)),
|
|
h("dt", null, t("verify.device")),
|
|
h("dd", { class: "mono" }, shortKey(l.device)),
|
|
),
|
|
h("p", { class: "muted" }, t("verify.limit")),
|
|
// Never echo the content of a listing that failed verification, not even as raw data.
|
|
v.ok && h("details", null, h("summary", null, t("verify.raw")), h("pre", null, JSON.stringify(raw, null, 2))),
|
|
);
|
|
}
|
|
|
|
function listingBody(l: Listing): HTMLElement[] {
|
|
const area = decodeGeohash(l.geohash);
|
|
const fact = (k: Key, v: string): Array<HTMLElement | false> =>
|
|
v ? [h("dt", null, t(k)), h("dd", null, v)] : [false];
|
|
const map =
|
|
area &&
|
|
h(
|
|
"a",
|
|
{
|
|
href: `https://www.openstreetmap.org/?mlat=${area.lat.toFixed(5)}&mlon=${area.lon.toFixed(5)}#map=14/${area.lat.toFixed(5)}/${area.lon.toFixed(5)}`,
|
|
target: "_blank",
|
|
rel: "noopener noreferrer",
|
|
},
|
|
t("detail.map"),
|
|
);
|
|
|
|
return [
|
|
h("div", { class: "detail-head" }, h("h1", null, l.title ?? ""), badge(true)),
|
|
h("p", { class: "price big" }, price(l)),
|
|
h(
|
|
"section",
|
|
{ class: "panel" },
|
|
h("h2", null, t("detail.facts")),
|
|
h(
|
|
"dl",
|
|
{ class: "kv" },
|
|
...(
|
|
[
|
|
...fact("detail.kind", label("kind", l.kind)),
|
|
...fact("detail.category", label("cat", l.category)),
|
|
...fact("detail.area", l.area_m2 ? t("card.area", { n: l.area_m2 }) : ""),
|
|
...fact("detail.rooms", l.rooms_x2 ? rooms(l.rooms_x2) : ""),
|
|
...fact("detail.published", date(l.created_at)),
|
|
...fact("detail.expires", date(l.expires_at)),
|
|
...fact("detail.version", String(l.seq)),
|
|
...fact("detail.location", where(l.geohash)),
|
|
].filter(Boolean) as HTMLElement[]
|
|
),
|
|
),
|
|
map && h("p", null, map),
|
|
),
|
|
l.description ? h("section", { class: "panel" }, h("p", { class: "desc" }, l.description)) : h("span"),
|
|
l.features?.length
|
|
? h("section", { class: "panel" }, h("h2", null, t("detail.features")), h("ul", { class: "chips" }, ...l.features.map((f) => h("li", null, f))))
|
|
: h("span"),
|
|
contactPanel(l),
|
|
reportPanel(l),
|
|
];
|
|
}
|
|
|
|
async function showDetail(author: string, id: string): Promise<void> {
|
|
const gen = state.generation;
|
|
clear(app);
|
|
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
|
|
app.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
|
|
|
|
let raw: unknown;
|
|
try {
|
|
raw = await getListing(author, id);
|
|
} catch {
|
|
if (gen !== state.generation) return;
|
|
clear(body);
|
|
body.append(h("p", { class: "error" }, t("results.error")));
|
|
return;
|
|
}
|
|
if (gen !== state.generation) return;
|
|
clear(body);
|
|
|
|
if (raw === null) {
|
|
body.append(h("p", { class: "muted" }, t("detail.notFound")));
|
|
return;
|
|
}
|
|
const l = raw as Listing;
|
|
let v = verifyListing(raw, verifyOpts());
|
|
// A gateway could answer with a different, validly signed listing.
|
|
if (v.ok && (l.author !== author || l.id !== id)) {
|
|
v = { ...v, ok: false, checks: [...v.checks, { id: "binding", ok: false, info: "not the listing that was requested" }] };
|
|
}
|
|
|
|
if (!v.ok) {
|
|
body.append(h("p", { class: "error" }, t("detail.unverified")), verification(raw, l, v));
|
|
return;
|
|
}
|
|
append(body, [...listingBody(l), verification(raw, l, v)]);
|
|
}
|
|
|
|
// --- boot -----------------------------------------------------------------
|
|
|
|
/** "My messages" is for buyers; "My listings" only appears once the owner has signed in. */
|
|
function renderNav(): void {
|
|
const nav = document.getElementById("nav")!;
|
|
clear(nav);
|
|
append(nav, [
|
|
h("a", { href: "#/messages" }, t("nav.messages")),
|
|
getToken() && h("a", { href: "#/mine" }, t("nav.owner")),
|
|
]);
|
|
}
|
|
|
|
function route(): void {
|
|
state.generation++;
|
|
const hash = location.hash.replace(/^#/, "") || "/";
|
|
const q = hash.indexOf("?");
|
|
const path = q < 0 ? hash : hash.slice(0, q);
|
|
const params = new URLSearchParams(q < 0 ? "" : hash.slice(q + 1));
|
|
const m = /^\/l\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(path);
|
|
const c = /^\/c\/([0-9a-f]{64})\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(path);
|
|
const login = /^\/login\/([0-9a-f]{16,128})$/.exec(path);
|
|
const own = /^\/mine(?:\/([0-9a-f]{32})(?:\/([0-9a-f]{64}))?)?$/.exec(path);
|
|
const edit = /^\/mine\/([0-9a-f]{32})\/edit$/.exec(path);
|
|
document.body.classList.remove("wide");
|
|
if (login) {
|
|
// The token came in the URL fragment: keep it for this tab and take it out of the address bar.
|
|
setToken(login[1]!);
|
|
if (state.node && state.node.regions.length === 0) {
|
|
// A node that follows nothing has nothing to show: the first thing to do is choose.
|
|
history.replaceState(null, "", location.pathname + location.search + "#/mine/regions");
|
|
showRegions();
|
|
} else {
|
|
history.replaceState(null, "", location.pathname + location.search + "#/mine");
|
|
void showOwner();
|
|
}
|
|
} 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/reports") void showReports();
|
|
else if (path === "/mine/new") void showPublish();
|
|
else if (edit) void showPublish(edit[1]);
|
|
else if (own) void showOwner(own[1], own[2]);
|
|
else showSearch(params);
|
|
renderNav();
|
|
window.scrollTo(0, 0);
|
|
}
|
|
|
|
async function boot(): Promise<void> {
|
|
document.documentElement.lang = lang;
|
|
document.getElementById("foot")!.textContent = t("footer.text");
|
|
try {
|
|
state.node = await getStatus();
|
|
statusEl.textContent = statusLine(state.node);
|
|
} catch {
|
|
statusEl.textContent = t("status.unreachable");
|
|
}
|
|
window.addEventListener("hashchange", route);
|
|
route();
|
|
}
|
|
|
|
void boot();
|