Publish, edit, renew and delete listings from the web UI

- Form at #/mine/new and #/mine/<id>/edit: coordinates pasted and encoded
  to a precision-6 geohash in the browser (about 1 km, OSM link to check, no
  map tiles), euro price parsing, optional exact address saved on the node only
- Region guard: refuses places the node does not follow; region fixed on edit
- Owner view: days left with a warning under 5 days, manual Renew (30 days),
  Edit, Delete with confirmation
- Tests (jsdom and pure logic), docs, rebuilt web/dist

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 20:18:08 +01:00
co-authored by Claude Sonnet 5.5
parent 7348067350
commit d021989f09
16 changed files with 1846 additions and 87 deletions
+640 -83
View File
@@ -267,6 +267,48 @@ var de = {
"own.needAddress": "Bitte gib eine Adresse ein.",
"own.loadError": "Konnte nicht geladen werden.",
"own.err": "Fehlgeschlagen: {detail}",
"own.new": "Neue Anzeige",
"own.edit": "Bearbeiten",
"own.renew": "Verl\xE4ngern",
"own.renewing": "Wird verl\xE4ngert \u2026",
"own.deleteListing": "Anzeige l\xF6schen",
"own.deleteListingSure": "Wirklich l\xF6schen? Die Anzeige verschwindet aus dem Netz, und Interessenten k\xF6nnen dich dar\xFCber nicht mehr erreichen.",
"own.daysLeft": "Noch {n} Tage",
"own.dayLeft": "Noch 1 Tag",
"own.expired": "Abgelaufen",
"own.soon": "L\xE4uft bald ab. \u201EVerl\xE4ngern\u201C stellt sie f\xFCr 30 Tage neu ein.",
"pub.createTitle": "Anzeige ver\xF6ffentlichen",
"pub.editTitle": "Anzeige bearbeiten",
"pub.intro": "Deine Anzeige wird signiert und an die Knoten deiner Region verteilt. Name, genaue Adresse und Kontaktdaten stehen nie darin.",
"pub.back": "\u2190 Zur\xFCck",
"pub.title": "Titel",
"pub.description": "Beschreibung",
"pub.priceRent": "Miete pro Monat (\u20AC)",
"pub.priceSale": "Kaufpreis (\u20AC)",
"pub.area": "Fl\xE4che in m\xB2 (optional)",
"pub.rooms": "Zimmer (optional, halbe Zimmer m\xF6glich)",
"pub.features": "Ausstattung (optional, mit Komma getrennt)",
"pub.location": "Lage",
"pub.locationHelp": "F\xFCge Koordinaten ein, zum Beispiel 53.5511, 9.9937 (in OpenStreetMap oder deiner Karten-App den Ort anklicken und kopieren; ein Link geht auch). Ver\xF6ffentlicht wird nur ein Gebiet von etwa einem Kilometer, nie die genaue Adresse.",
"pub.useLocation": "Meinen Standort verwenden",
"pub.locationShown": "Ver\xF6ffentlicht wird ein Gebiet von etwa {w} \xD7 {h} m um {lat}, {lon} (Code {hash}).",
"pub.duration": "Sichtbar f\xFCr",
"pub.addrTitle": "Genaue Adresse (optional)",
"pub.addrHelp": "Bleibt auf deinem Knoten und wird nie ver\xF6ffentlicht. Du gibst sie sp\xE4ter einzelnen Interessenten frei.",
"pub.publish": "Ver\xF6ffentlichen",
"pub.save": "\xC4nderungen speichern",
"pub.working": "Wird ver\xF6ffentlicht \u2026 (eine kleine Rechenaufgabe, ein paar Sekunden)",
"pub.notFound": "Diese Anzeige gibt es nicht (mehr).",
"pub.eTitle": "Bitte gib einen Titel an (h\xF6chstens 120 Zeichen, eine Zeile).",
"pub.eDescription": "Die Beschreibung ist zu lang (h\xF6chstens 4000 Zeichen) oder enth\xE4lt unerlaubte Zeichen.",
"pub.ePrice": "Bitte gib einen Betrag gr\xF6\xDFer als 0 an, zum Beispiel 1150 oder 1.150,50.",
"pub.eArea": "Die Fl\xE4che muss eine ganze Zahl sein (h\xF6chstens 100000).",
"pub.eRooms": "Zimmer: eine Zahl in halben Schritten, zum Beispiel 2,5.",
"pub.eFeatures": "H\xF6chstens 20 Merkmale mit je h\xF6chstens 40 Zeichen.",
"pub.eLocation": "Die Koordinaten konnten nicht gelesen werden. Beispiel: 53.5511, 9.9937",
"pub.eRegion": "Dein Knoten folgt der Region {region} nicht, du w\xFCrdest also keine Nachrichten zu dieser Anzeige erhalten. Starte den Knoten mit --region {region} oder w\xE4hle einen Ort in {regions}.",
"pub.eRegionEdit": "Die Region einer Anzeige l\xE4sst sich nicht \xE4ndern. L\xF6sche sie und lege eine neue an.",
"pub.eAddress": "Die Adresse ist zu lang (h\xF6chstens 300 Bytes).",
"verify.title": "Pr\xFCfung in deinem Browser",
"verify.intro": "Diese Pr\xFCfung l\xE4uft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt f\xE4lschen.",
"verify.limit": "Nicht pr\xFCfbar: ob der Anbieter sein Ger\xE4t inzwischen gesperrt hat. Das wei\xDF nur das Netzwerk; dein Knoten kennt den aktuellen Stand.",
@@ -448,6 +490,48 @@ var en = {
"own.needAddress": "Please enter an address.",
"own.loadError": "Could not be loaded.",
"own.err": "Failed: {detail}",
"own.new": "New listing",
"own.edit": "Edit",
"own.renew": "Renew",
"own.renewing": "Renewing \u2026",
"own.deleteListing": "Delete listing",
"own.deleteListingSure": "Really delete? The listing disappears from the network, and people can no longer reach you through it.",
"own.daysLeft": "{n} days left",
"own.dayLeft": "1 day left",
"own.expired": "Expired",
"own.soon": 'Expires soon. "Renew" publishes it again for 30 days.',
"pub.createTitle": "Publish a listing",
"pub.editTitle": "Edit listing",
"pub.intro": "Your listing is signed and spread to the nodes of your region. It never contains your name, exact address or contact details.",
"pub.back": "\u2190 Back",
"pub.title": "Title",
"pub.description": "Description",
"pub.priceRent": "Rent per month (\u20AC)",
"pub.priceSale": "Price (\u20AC)",
"pub.area": "Area in m\xB2 (optional)",
"pub.rooms": "Rooms (optional, half rooms allowed)",
"pub.features": "Features (optional, separated by commas)",
"pub.location": "Location",
"pub.locationHelp": "Paste coordinates, for example 53.5511, 9.9937 (click the place in OpenStreetMap or your map app and copy; a link works too). Only an area of about a kilometre is published, never the exact address.",
"pub.useLocation": "Use my location",
"pub.locationShown": "An area of about {w} \xD7 {h} m around {lat}, {lon} will be published (code {hash}).",
"pub.duration": "Visible for",
"pub.addrTitle": "Exact address (optional)",
"pub.addrHelp": "Stays on your node and is never published. You release it to individual people later.",
"pub.publish": "Publish",
"pub.save": "Save changes",
"pub.working": "Publishing \u2026 (a small puzzle, a few seconds)",
"pub.notFound": "This listing does not exist (any more).",
"pub.eTitle": "Please enter a title (at most 120 characters, one line).",
"pub.eDescription": "The description is too long (at most 4000 characters) or contains characters that are not allowed.",
"pub.ePrice": "Please enter an amount above 0, for example 1150 or 1,150.50.",
"pub.eArea": "The area must be a whole number (at most 100000).",
"pub.eRooms": "Rooms: a number in half steps, for example 2.5.",
"pub.eFeatures": "At most 20 features of at most 40 characters each.",
"pub.eLocation": "The coordinates could not be read. Example: 53.5511, 9.9937",
"pub.eRegion": "Your node does not follow region {region}, so you would not receive messages about this listing. Start the node with --region {region} or choose a place in {regions}.",
"pub.eRegionEdit": "A listing's region cannot change. Delete it and create a new one.",
"pub.eAddress": "The address is too long (at most 300 bytes).",
"verify.title": "Checked in your browser",
"verify.intro": "This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
"verify.limit": "Cannot be checked: whether the owner has since revoked their device. Only the network knows that; your node has the current state.",
@@ -524,6 +608,59 @@ function decodeGeohash(hash) {
lonErr: (lon[1] - lon[0]) / 2
};
}
function encodeGeohash(lat, lon, precision = 6) {
let latR = [-90, 90];
let lonR = [-180, 180];
let out = "";
let bits = 0;
let value = 0;
let evenBit = true;
while (out.length < precision) {
const range = evenBit ? lonR : latR;
const x = evenBit ? lon : lat;
const mid = (range[0] + range[1]) / 2;
value <<= 1;
if (x >= mid) {
value |= 1;
range[0] = mid;
} else {
range[1] = mid;
}
evenBit = !evenBit;
if (++bits === 5) {
out += ALPHABET[value];
bits = 0;
value = 0;
}
}
return out;
}
var NUM = String.raw`[-+]?\d{1,3}(?:\.\d+)?`;
function parseCoordinates(input) {
const s = input.trim();
let a;
let b;
let m;
if (m = new RegExp(String.raw`#map=\d+/(${NUM})/(${NUM})`).exec(s)) [, a, b] = m;
else if (m = new RegExp(String.raw`mlat=(${NUM})&(?:amp;)?mlon=(${NUM})`).exec(s)) [, a, b] = m;
else if (m = new RegExp(String.raw`@(${NUM}),(${NUM})`).exec(s)) [, a, b] = m;
else if (m = new RegExp(String.raw`^(${NUM})\s*[,;]\s*(${NUM})$`).exec(s)) [, a, b] = m;
else if (m = /^([-+]?\d{1,3},\d+)\s*;\s*([-+]?\d{1,3},\d+)$/.exec(s)) [, a, b] = m.map((x) => x?.replace(",", "."));
else if (m = /^([-+]?\d{1,3}[.,]\d+)\s+([-+]?\d{1,3}[.,]\d+)$/.exec(s)) [, a, b] = m.map((x) => x?.replace(",", "."));
if (a === void 0 || b === void 0) return null;
const lat = Number(a);
const lon = Number(b);
if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
return { lat, lon };
}
function cellMetres(hash) {
const a = decodeGeohash(hash);
if (!a) return null;
return {
height: Math.round(a.latErr * 2 * 111320),
width: Math.round(a.lonErr * 2 * 111320 * Math.cos(a.lat * Math.PI / 180))
};
}
// node_modules/@noble/ciphers/utils.js
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
@@ -548,11 +685,11 @@ function abytes(value, length, title = "") {
return value;
if (length !== void 0)
anumber(length, "length");
const bytes = isBytes(value);
const bytes2 = isBytes(value);
const ofLen = length !== void 0 ? ` of length ${length}` : "";
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
const got = bytes2 ? `length=${value.length}` : `type=${typeof value}`;
const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
if (!bytes)
if (!bytes2)
throw new TypeError(message);
throw new RangeError(message);
}
@@ -697,11 +834,11 @@ function u64Lengths(dataLength, aadLength, isLE2) {
view.setBigUint64(8, BigInt(dataLength), isLE2);
return num2;
}
function isAligned32(bytes) {
return bytes.byteOffset % 4 === 0;
function isAligned32(bytes2) {
return bytes2.byteOffset % 4 === 0;
}
function copyBytes(bytes) {
return Uint8Array.from(abytes(bytes));
function copyBytes(bytes2) {
return Uint8Array.from(abytes(bytes2));
}
// node_modules/@noble/ciphers/_arx.js
@@ -1295,11 +1432,11 @@ function abytes2(value, length, title = "") {
return value;
if (length !== void 0)
anumber2(length, "length");
const bytes = isBytes2(value);
const bytes2 = isBytes2(value);
const ofLen = length !== void 0 ? ` of length ${length}` : "";
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
const got = bytes2 ? `length=${value.length}` : `type=${typeof value}`;
const message = atitle2(title) + "expected Uint8Array" + ofLen + ", got " + got;
if (!bytes)
if (!bytes2)
throw new TypeError(message);
throw new RangeError(message);
}
@@ -1352,13 +1489,13 @@ var hasHexBuiltin = /* @__PURE__ */ (() => (
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
))();
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
function bytesToHex(bytes) {
abytes2(bytes);
function bytesToHex(bytes2) {
abytes2(bytes2);
if (hasHexBuiltin)
return bytes.toHex();
return bytes2.toHex();
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
for (let i = 0; i < bytes2.length; i++) {
hex += hexes[bytes2[i]];
}
return hex;
}
@@ -2029,11 +2166,11 @@ function hexToNumber(hex) {
throw new TypeError("hex string expected, got " + typeof hex);
return hex === "" ? _0n : BigInt("0x" + hex);
}
function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
function bytesToNumberBE(bytes2) {
return hexToNumber(bytesToHex(bytes2));
}
function bytesToNumberLE(bytes) {
return hexToNumber(bytesToHex(copyBytes2(abytes2(bytes)).reverse()));
function bytesToNumberLE(bytes2) {
return hexToNumber(bytesToHex(copyBytes2(abytes2(bytes2)).reverse()));
}
function numberToBytesBE(n, len) {
anumber2(len);
@@ -2049,8 +2186,8 @@ function numberToBytesBE(n, len) {
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
function copyBytes2(bytes) {
return Uint8Array.from(abytes3(bytes));
function copyBytes2(bytes2) {
return Uint8Array.from(abytes3(bytes2));
}
function isPosBig(n) {
return typeof n === "bigint" && _0n <= n;
@@ -2320,19 +2457,19 @@ var FIELD_FIELDS = [
"mulN",
"sqrN"
];
function validateField(field2) {
aobject3(field2, "field");
if (typeof field2.ORDER !== "bigint")
throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field2.ORDER);
asafenumber(field2.BYTES, "BYTES");
asafenumber(field2.BITS, "BITS");
function validateField(field3) {
aobject3(field3, "field");
if (typeof field3.ORDER !== "bigint")
throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field3.ORDER);
asafenumber(field3.BYTES, "BYTES");
asafenumber(field3.BITS, "BITS");
for (const name of FIELD_FIELDS)
afunction(field2[name], "field." + name);
if (field2.BYTES < 1 || field2.BITS < 1)
afunction(field3[name], "field." + name);
if (field3.BYTES < 1 || field3.BITS < 1)
throw new Error("invalid field: expected BYTES/BITS > 0");
if (field2.ORDER <= _1n2)
throw new Error("invalid field: expected ORDER > 1, got " + field2.ORDER);
return field2;
if (field3.ORDER <= _1n2)
throw new Error("invalid field: expected ORDER > 1, got " + field3.ORDER);
return field3;
}
function FpInvertBatch(Fp2, nums, passZero = false) {
validateField(Fp2);
@@ -2484,20 +2621,20 @@ var _Field = class {
toBytes(num2) {
return this.isLE ? numberToBytesLE(num2, this.BYTES) : numberToBytesBE(num2, this.BYTES);
}
fromBytes(bytes, skipValidation = false) {
abytes3(bytes);
fromBytes(bytes2, skipValidation = false) {
abytes3(bytes2);
const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
if (allowedLengths) {
if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
if (bytes2.length < 1 || !allowedLengths.includes(bytes2.length) || bytes2.length > BYTES) {
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes2.length);
}
const padded = new Uint8Array(BYTES);
padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
bytes = padded;
padded.set(bytes2, isLE2 ? 0 : padded.length - bytes2.length);
bytes2 = padded;
}
if (bytes.length !== BYTES)
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
if (bytes2.length !== BYTES)
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes2.length);
let scalar = isLE2 ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2);
if (modFromBytes)
scalar = mod(scalar, ORDER);
if (!skipValidation) {
@@ -2554,9 +2691,9 @@ function validateW(W, bits, min = 1) {
throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
}
function validateTableBytes(numPoints, fpBytes) {
const bytes = numPoints * (4 * fpBytes + 128);
if (bytes > TABLE_BYTES_MAX)
throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
const bytes2 = numPoints * (4 * fpBytes + 128);
if (bytes2 > TABLE_BYTES_MAX)
throw new Error("invalid window size: table would need ~" + Math.ceil(bytes2 / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
}
function probeRandomBytes(randomBytes4, length) {
if (randomBytes4 === void 0)
@@ -2578,11 +2715,11 @@ function validateMSMPoints(points, c) {
throw new Error("invalid point at index " + i);
});
}
function validateMSMScalars(scalars, field2, maxScalar) {
function validateMSMScalars(scalars, field3, maxScalar) {
if (!Array.isArray(scalars))
throw new Error("array of scalars expected");
scalars.forEach((s, i) => {
const ok = maxScalar === void 0 ? field2.isValid(s) : isPosBig(s) && s < maxScalar;
const ok = maxScalar === void 0 ? field3.isValid(s) : isPosBig(s) && s < maxScalar;
if (!ok)
throw new Error("invalid scalar at index " + i);
});
@@ -2869,12 +3006,12 @@ function mulAddUnsafe(c, points, scalars, allowOversized = false) {
const digits = scalars.map((n) => wnafDigits(n, 4));
return wnafWalk(c.ZERO, tables, digits);
}
function createField(order, field2, isLE2) {
if (field2) {
if (field2.ORDER !== order)
function createField(order, field3, isLE2) {
if (field3) {
if (field3.ORDER !== order)
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
validateField(field2);
return field2;
validateField(field3);
return field3;
} else {
return Field(order, { isLE: isLE2 });
}
@@ -2995,13 +3132,13 @@ function edwards(params, extraOpts = {}) {
return new Point(x, y, Fp2.ONE, Fp2.mul(x, y));
}
// Uses algo from RFC8032 5.1.3.
static fromBytes(bytes, zip215 = false) {
static fromBytes(bytes2, zip215 = false) {
const len = Fp2.BYTES;
const { a, d } = CURVE;
bytes = copyBytes2(abytes3(bytes, len, "point"));
bytes2 = copyBytes2(abytes3(bytes2, len, "point"));
abool2(zip215, "zip215");
const normed = copyBytes2(bytes);
const lastByte = bytes[len - 1];
const normed = copyBytes2(bytes2);
const lastByte = bytes2[len - 1];
normed[len - 1] = lastByte & ~128;
const y = bytesToNumberLE(normed);
const max = zip215 ? MASK : Fp2.ORDER;
@@ -3185,9 +3322,9 @@ function edwards(params, extraOpts = {}) {
}
toBytes() {
const { x, y } = this.toAffine();
const bytes = Fp2.toBytes(y);
bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
return bytes;
const bytes2 = Fp2.toBytes(y);
bytes2[bytes2.length - 1] |= isOdd(x) ? 128 : 0;
return bytes2;
}
toHex() {
return bytesToHex2(this.toBytes());
@@ -3232,7 +3369,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
const randomBytes4 = opts.randomBytes === void 0 ? randomBytes3 : opts.randomBytes;
const toMontgomery2 = opts.toMontgomery;
const toMontgomerySecret2 = opts.toMontgomerySecret;
const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes2) => bytes2 : opts.adjustScalarBytes;
const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
abool2(phflag, "phflag");
if (ctx.length || phflag)
@@ -3545,11 +3682,11 @@ function ed25519_pow_2_252_3(x) {
const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
return { pow_p_5_8, b2 };
}
function adjustScalarBytes(bytes) {
bytes[0] &= 248;
bytes[31] &= 127;
bytes[31] |= 64;
return bytes;
function adjustScalarBytes(bytes2) {
bytes2[0] &= 248;
bytes2[31] &= 127;
bytes2[31] |= 64;
return bytes2;
}
var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
function uvRatio(u, v) {
@@ -3757,17 +3894,17 @@ var MAX_CERT_LIFETIME = 366 * DAY;
var MAX_LISTING_LIFETIME = 30 * DAY;
var MAX_CLOCK_SKEW = 10 * 60;
var enc = new TextEncoder();
function hexBytes(s, bytes) {
if (typeof s !== "string" || s.length !== bytes * 2 || !/^[0-9a-f]+$/.test(s)) {
function hexBytes(s, bytes2) {
if (typeof s !== "string" || s.length !== bytes2 * 2 || !/^[0-9a-f]+$/.test(s)) {
return null;
}
const out = new Uint8Array(bytes);
for (let i = 0; i < bytes; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
const out = new Uint8Array(bytes2);
for (let i = 0; i < bytes2; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
return out;
}
function leadingZeroBits(bytes) {
function leadingZeroBits(bytes2) {
let n = 0;
for (const b of bytes) {
for (const b of bytes2) {
if (b === 0) {
n += 8;
continue;
@@ -4522,6 +4659,26 @@ function showInbox() {
]);
}
// src/draft.ts
var MAX_LIFETIME_DAYS = 30;
function draftFromListing(l, days = MAX_LIFETIME_DAYS) {
const period = l.price?.period === "once" ? "once" : "month";
const d = {
kind: l.kind ?? "",
category: l.category ?? "",
geohash: l.geohash,
price: { amount_cents: l.price?.amount_cents ?? 0, currency: "EUR", period },
area_m2: l.area_m2 ?? 0,
rooms_x2: l.rooms_x2 ?? 0,
features: l.features ?? [],
title: l.title ?? "",
description: l.description ?? "",
expires_in_days: days
};
if (l.delegate) d.delegate = l.delegate;
return d;
}
// src/ownerApi.ts
var TOKEN_KEY = "allmende.owner.token";
var memory = null;
@@ -4609,6 +4766,23 @@ async function putAddress(listing, a) {
async function deleteAddress(listing) {
await call("DELETE", `/api/v1/listings/${e(listing)}/address`);
}
async function createListing(d) {
return await call("POST", "/api/v1/listings", d);
}
async function updateListing(id, d) {
return await call("PUT", `/api/v1/listings/${e(id)}`, d);
}
async function deleteListing(id) {
await call("DELETE", `/api/v1/listings/${e(id)}`);
}
async function getOwnListing(author, id) {
return await getListing(author, id);
}
async function renewListing(author, id, days = MAX_LIFETIME_DAYS) {
const l = await getOwnListing(author, id);
if (!l || l.tombstone) throw new HttpError(404, "no such listing of yours");
return updateListing(id, draftFromListing(l, days));
}
// src/owner.ts
var REFRESH_MS = 3e4;
@@ -4670,6 +4844,7 @@ async function showOwner(listingId, thread) {
"section",
{ class: "pane pane-listings" },
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("button", { type: "button", class: "btn", onclick: logout }, t("own.logout")))
);
@@ -4677,12 +4852,14 @@ async function showOwner(listingId, thread) {
const chips = h("div", { class: "chips-row" });
const reqBox = h("div", { class: "olist" });
const addr = listingId ? addressCard(listingId, () => void refresh()) : null;
const bar = listingId ? listingBar(listingId, () => void refresh()) : null;
const requestsPane = h("section", { class: "pane pane-requests" });
append(
requestsPane,
listingId ? [
h("a", { class: "back narrow-only", href: "#/mine" }, t("own.backListings")),
reqTitle,
bar.root,
addr.root,
chips,
reqBox,
@@ -4725,7 +4902,8 @@ async function showOwner(listingId, thread) {
"span",
{ class: "badges" },
m.needs_reply > 0 ? h("span", { class: "badge warn" }, t("own.needReply", { n: m.needs_reply })) : m.threads === 0 ? h("span", { class: "badge muted" }, t("own.noRequests")) : h("span", { class: "badge ok" }, t("own.allAnswered")),
m.address_saved ? h("span", { class: "badge ok" }, t("own.addressSaved")) : h("span", { class: "badge warn" }, t("own.noAddress"))
m.address_saved ? h("span", { class: "badge ok" }, t("own.addressSaved")) : h("span", { class: "badge warn" }, t("own.noAddress")),
lifetimeBadge(m.expires_at)
)
)
);
@@ -4755,6 +4933,7 @@ async function showOwner(listingId, thread) {
function renderRequests() {
const m = mine2.find((x) => x.id === listingId);
reqTitle.textContent = m?.title ?? "";
bar?.update(m);
const counts = { all: threads.length, reply: threads.filter((x) => x.needs_reply).length, hidden: threads.filter((x) => x.hidden > 0).length };
clear(chips);
for (const [f, key] of [["all", "own.filterAll"], ["reply", "own.filterReply"], ["hidden", "own.filterHidden"]]) {
@@ -4833,6 +5012,81 @@ async function showOwner(listingId, thread) {
};
tick2();
}
var DAY2 = 86400;
var SOON_DAYS = 5;
var daysLeft = (expiresAt) => Math.ceil((expiresAt - nowSeconds()) / DAY2);
function lifetimeBadge(expiresAt) {
const n = daysLeft(expiresAt);
if (n <= 0) return h("span", { class: "badge bad" }, t("own.expired"));
return h("span", { class: `badge ${n < SOON_DAYS ? "warn" : "muted"}` }, n === 1 ? t("own.dayLeft") : t("own.daysLeft", { n }));
}
function listingBar(listingId, changed) {
const root = h("div", { class: "listing-bar" });
const problem = h("p", { class: "error", role: "alert" });
let current;
let renewing = false;
function render() {
clear(root);
if (!current) return;
const soon = daysLeft(current.expires_at) < SOON_DAYS;
const renew = h("button", { type: "button", class: `btn${soon ? " primary" : ""}`, onclick: () => void doRenew(renew) }, t("own.renew"));
const del = h("span", null);
const ask = () => {
clear(del);
append(del, [
t("own.deleteListingSure"),
" ",
h(
"button",
{
type: "button",
class: "btn",
onclick: () => void deleteListing(listingId).then(() => {
location.hash = "#/mine";
}).catch((e2) => {
problem.textContent = e2 instanceof Unauthorized ? t("own.loginBad") : explain(e2);
})
},
t("own.deleteYes")
)
]);
};
del.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.deleteListing")));
append(root, [
h("p", { class: "badges" }, lifetimeBadge(current.expires_at)),
soon && h("p", { class: "note warn" }, t("own.soon")),
h("div", { class: "actions" }, h("a", { class: "btn", href: `#/mine/${listingId}/edit` }, t("own.edit")), renew, del),
problem
]);
}
async function doRenew(button) {
if (renewing) return;
renewing = true;
problem.textContent = "";
button.disabled = true;
button.textContent = t("own.renewing");
try {
const author = state.node?.author;
if (!author) throw new Error("node unknown");
await renewListing(author, listingId);
changed();
} catch (e2) {
problem.textContent = e2 instanceof Unauthorized ? t("own.loginBad") : explain(e2);
button.disabled = false;
button.textContent = t("own.renew");
} finally {
renewing = false;
}
}
return {
root,
update(m) {
if (m?.expires_at === current?.expires_at && root.firstChild) return;
current = m;
render();
}
};
}
var ASKS_ADDRESS = /adress|address|anschrift|wo genau|wo liegt|wo befindet|which street|what street|where exactly|where is|where in/i;
function asksForAddress(msgs) {
const last = msgs[msgs.length - 1];
@@ -5082,10 +5336,310 @@ function openSheet(listingId, thread, opener, done) {
);
}
// src/parse.ts
function parseEuros(input) {
const s = input.replace(/[€\s ]|eur/gi, "");
if (!/^\d[\d.,]*$/.test(s)) return null;
const lastDot = s.lastIndexOf(".");
const lastComma = s.lastIndexOf(",");
let whole;
let frac = "";
if (lastDot >= 0 && lastComma >= 0) {
const at = Math.max(lastDot, lastComma);
whole = s.slice(0, at);
frac = s.slice(at + 1);
} else if (lastDot >= 0 || lastComma >= 0) {
const sep = lastDot >= 0 ? "." : ",";
const parts = s.split(sep);
const last = parts[parts.length - 1];
if (parts.length > 2 || last.length === 3) {
whole = parts.join("");
} else {
whole = parts.slice(0, -1).join("");
frac = last;
}
} else {
whole = s;
}
whole = whole.replace(/[.,]/g, "");
if (!/^\d+$/.test(whole) || frac !== "" && !/^\d{1,2}$/.test(frac)) return null;
const cents = Number(whole) * 100 + Number(frac.padEnd(2, "0") || "0");
return Number.isSafeInteger(cents) && cents > 0 ? cents : null;
}
function parseRoomsX2(input) {
const s = input.trim().replace(",", ".");
if (s === "") return null;
const n = Number(s);
if (!Number.isFinite(n) || n < 0 || n > 100 || !Number.isInteger(n * 2)) return null;
return n * 2;
}
// src/publish.ts
var app3 = () => document.getElementById("app");
var DURATIONS = [7, 14, 21, MAX_LIFETIME_DAYS];
var KINDS = ["rent", "sale"];
var CATEGORIES = ["apartment", "house", "room", "commercial"];
var MAX_TITLE = 120;
var MAX_DESCRIPTION = 4e3;
var MAX_FEATURES = 20;
var MAX_FEATURE = 40;
var MAX_AREA = 1e5;
var MAX_ADDRESS_BYTES = 300;
var chars = (s) => [...s].length;
var bytes = (s) => new TextEncoder().encode(s).length;
var hasControl = (s, newlines) => newlines ? /[\p{Cc}]/u.test(s.replace(/\n/g, "")) : /\p{Cc}/u.test(s);
function explain2(e2) {
return t("own.err", { detail: e2 instanceof HttpError ? e2.detail : e2 instanceof Error ? e2.message : "?" });
}
function field(label2, control, help) {
const err = h("p", { class: "error", role: "alert" });
const root = h("div", { class: "field" }, h("label", null, label2, control), help && h("p", { class: "muted small" }, help), err);
return {
root,
control,
error(msg) {
err.textContent = msg ?? "";
if (msg) control.setAttribute("aria-invalid", "true");
else control.removeAttribute("aria-invalid");
}
};
}
var euros = (cents) => (cents / 100).toLocaleString(lang, { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2, useGrouping: false });
async function showPublish(editId) {
const gen = state.generation;
if (!getToken()) {
renderLogin(false);
return;
}
const root = app3();
document.body.classList.remove("wide");
clear(root);
let old = null;
if (editId) {
root.append(h("p", { class: "muted" }, t("results.loading")));
try {
const author = state.node?.author;
if (!author) throw new Error("node unknown");
old = await getOwnListing(author, editId);
} catch (e2) {
if (gen !== state.generation) return;
clear(root);
root.append(h("p", { class: "error" }, t("own.loadError")));
return;
}
if (gen !== state.generation) return;
clear(root);
if (!old || old.tombstone) {
root.append(h("a", { class: "back", href: "#/mine" }, t("pub.back")), h("p", { class: "muted" }, t("pub.notFound")));
return;
}
}
const radios = KINDS.map((k) => h("input", { type: "radio", name: "kind", value: k, checked: (old?.kind ?? "rent") === k }));
const kindField = h(
"fieldset",
{ class: "field" },
h("legend", null, t("filter.kind")),
h("div", { class: "radios" }, ...radios.map((r) => h("label", { class: "check" }, r, " ", t(`kind.${r.value}`))))
);
const kind = () => radios.find((r) => r.checked)?.value ?? "rent";
const category = field(
t("filter.category"),
h("select", { name: "category" }, ...CATEGORIES.map((c) => h("option", { value: c, selected: (old?.category ?? "apartment") === c }, t(`cat.${c}`))))
);
const title = field(t("pub.title"), h("input", { name: "title", maxlength: MAX_TITLE * 2, value: old?.title ?? "", autocomplete: "off" }));
const description = field(t("pub.description"), h("textarea", { name: "description", rows: 7 }, old?.description ?? ""));
const priceLabel = h("span", null, t("pub.priceRent"));
const priceInput = h("input", { name: "price", inputmode: "decimal", value: old?.price ? euros(old.price.amount_cents) : "", autocomplete: "off" });
const price2 = field("", priceInput);
price2.root.querySelector("label").prepend(priceLabel);
const area = field(t("pub.area"), h("input", { name: "area", inputmode: "numeric", value: old?.area_m2 ? String(old.area_m2) : "" }));
const rooms2 = field(t("pub.rooms"), h("input", { name: "rooms", inputmode: "decimal", value: old?.rooms_x2 ? (old.rooms_x2 / 2).toLocaleString(lang) : "" }));
const features = field(t("pub.features"), h("input", { name: "features", value: (old?.features ?? []).join(", "), autocomplete: "off" }));
const syncKind = () => {
priceLabel.textContent = t(kind() === "rent" ? "pub.priceRent" : "pub.priceSale");
};
for (const r of radios) r.addEventListener("change", syncKind);
const here = old ? decodeGeohash(old.geohash) : null;
const locInput = h("input", {
name: "location",
inputmode: "decimal",
autocomplete: "off",
spellcheck: "false",
placeholder: "53.5511, 9.9937",
value: here ? `${here.lat.toFixed(5)}, ${here.lon.toFixed(5)}` : ""
});
const location_ = field(t("pub.location"), locInput, t("pub.locationHelp"));
const locPreview = h("p", { class: "muted small", "aria-live": "polite" });
const showLocation = () => {
clear(locPreview);
const pos = parseCoordinates(locInput.value);
if (!pos) return;
const g = encodeGeohash(pos.lat, pos.lon);
const c = cellMetres(g);
const a = decodeGeohash(g);
append(locPreview, [
t("pub.locationShown", { w: c?.width ?? 0, h: c?.height ?? 0, lat: a.lat.toFixed(3), lon: a.lon.toFixed(3), hash: g }),
" ",
h(
"a",
{
href: `https://www.openstreetmap.org/?mlat=${a.lat.toFixed(5)}&mlon=${a.lon.toFixed(5)}#map=15/${a.lat.toFixed(5)}/${a.lon.toFixed(5)}`,
target: "_blank",
rel: "noopener noreferrer"
},
t("detail.map")
)
]);
};
locInput.addEventListener("input", showLocation);
showLocation();
const locate = typeof navigator !== "undefined" && navigator.geolocation && window.isSecureContext ? h(
"button",
{
type: "button",
class: "btn",
onclick: () => navigator.geolocation.getCurrentPosition((p) => {
locInput.value = `${p.coords.latitude.toFixed(5)}, ${p.coords.longitude.toFixed(5)}`;
showLocation();
})
},
t("pub.useLocation")
) : null;
const duration = field(
t("pub.duration"),
h("select", { name: "days" }, ...DURATIONS.map((d) => h("option", { value: String(d), selected: d === MAX_LIFETIME_DAYS }, t("own.days", { n: d }))))
);
const addr = field(t("own.fAddress"), h("input", { name: "address", autocomplete: "off" }));
const phone = field(t("own.fPhone"), h("input", { name: "phone", maxlength: 40, autocomplete: "off" }));
const email = field(t("own.fEmail"), h("input", { name: "email", type: "email", maxlength: 120, autocomplete: "off" }));
const formError = h("p", { class: "error", role: "alert" });
const submit = h("button", { type: "submit", class: "btn primary" }, t(editId ? "pub.save" : "pub.publish"));
let busy = false;
function read() {
const fields = [title, description, price2, area, rooms2, features, location_, addr];
for (const f of fields) f.error(null);
const bad = [];
const val = (el) => el.value;
const titleText = val(title.control).trim();
if (!titleText || chars(titleText) > MAX_TITLE || hasControl(titleText, false)) bad.push([title, t("pub.eTitle")]);
const desc = val(description.control).replace(/\r\n?/g, "\n").trim();
if (chars(desc) > MAX_DESCRIPTION || hasControl(desc, true)) bad.push([description, t("pub.eDescription")]);
const cents = parseEuros(val(price2.control));
if (cents === null) bad.push([price2, t("pub.ePrice")]);
const areaText = val(area.control).trim();
const areaM2 = areaText === "" ? 0 : /^\d+$/.test(areaText) ? Number(areaText) : -1;
if (areaM2 < 0 || areaM2 > MAX_AREA) bad.push([area, t("pub.eArea")]);
const roomsText = val(rooms2.control).trim();
const roomsX2 = roomsText === "" ? 0 : parseRoomsX2(roomsText);
if (roomsX2 === null) bad.push([rooms2, t("pub.eRooms")]);
const list = [...new Set(val(features.control).split(/[,\n]/).map((s) => s.trim()).filter(Boolean))];
if (list.length > MAX_FEATURES || list.some((f) => chars(f) > MAX_FEATURE || hasControl(f, false))) bad.push([features, t("pub.eFeatures")]);
let geohash = "";
const pos = parseCoordinates(val(location_.control));
if (!pos) {
bad.push([location_, t("pub.eLocation")]);
} else {
geohash = encodeGeohash(pos.lat, pos.lon);
const region = geohash.slice(0, 3);
const followed = state.node?.regions;
if (old && old.geohash.slice(0, 3) !== region) bad.push([location_, t("pub.eRegionEdit")]);
else if (followed && followed.length > 0 && !followed.includes(region)) {
bad.push([location_, t("pub.eRegion", { region, regions: followed.join(", ") })]);
}
}
const address = val(addr.control).trim();
if (!editId && address && (bytes(address) > MAX_ADDRESS_BYTES || hasControl(address, true))) bad.push([addr, t("pub.eAddress")]);
if (bad.length > 0 || cents === null || roomsX2 === null) {
for (const [f, msg] of bad) f.error(msg);
bad[0]?.[0].control.focus();
return null;
}
const k = kind();
const draft = {
kind: k,
category: val(category.control),
geohash,
price: { amount_cents: cents, currency: "EUR", period: k === "rent" ? "month" : "once" },
area_m2: areaM2,
rooms_x2: roomsX2,
features: list,
title: titleText,
description: desc,
expires_in_days: Number(val(duration.control))
};
if (old?.delegate) draft.delegate = old.delegate;
const out = { draft };
if (!editId && address) {
out.address = { address, phone: val(phone.control).trim() || void 0, email: val(email.control).trim() || void 0 };
}
return out;
}
const form = h(
"form",
{
class: "form",
novalidate: true,
onsubmit: (ev) => {
ev.preventDefault();
if (busy) return;
const r = read();
if (!r) return;
void (async () => {
busy = true;
formError.textContent = "";
submit.disabled = true;
submit.textContent = t("pub.working");
try {
const l = editId ? await updateListing(editId, r.draft) : await createListing(r.draft);
if (r.address) {
await putAddress(l.id, r.address).catch(() => void 0);
}
if (gen === state.generation) location.hash = `#/mine/${l.id}`;
} catch (e2) {
if (e2 instanceof Unauthorized) renderLogin(true);
else formError.textContent = explain2(e2);
submit.disabled = false;
submit.textContent = t(editId ? "pub.save" : "pub.publish");
} finally {
busy = false;
}
})();
}
},
kindField,
category.root,
title.root,
description.root,
h("div", { class: "grid3" }, price2.root, area.root, rooms2.root),
features.root,
location_.root,
h("div", { class: "actions" }, locate),
locPreview,
duration.root,
!editId && h(
"section",
{ class: "panel" },
h("h2", null, t("pub.addrTitle")),
h("p", { class: "muted small" }, t("pub.addrHelp")),
addr.root,
h("div", { class: "grid2" }, phone.root, email.root)
),
formError,
h("div", { class: "actions" }, submit, h("a", { class: "btn", href: editId ? `#/mine/${editId}` : "#/mine" }, t("own.addrCancel")))
);
append(root, [
h("a", { class: "back", href: editId ? `#/mine/${editId}` : "#/mine" }, t("pub.back")),
h("h1", null, t(editId ? "pub.editTitle" : "pub.createTitle")),
h("p", { class: "muted" }, t("pub.intro")),
form
]);
syncKind();
}
// src/main.ts
var PAGE = 20;
var GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
var app3 = document.getElementById("app");
var app4 = document.getElementById("app");
var statusEl = document.getElementById("status");
function label(prefix, value) {
if (!value) return "";
@@ -5121,7 +5675,7 @@ function toApi(p) {
if (r) q.set("min_rooms", String(Math.ceil(r * 2)));
return q;
}
function field(text, input, hint) {
function field2(text, input, hint) {
return h("label", { class: "field" }, h("span", { class: "field-label" }, text), input, hint && h("span", { class: "hint" }, hint));
}
function select(name, current, options) {
@@ -5137,8 +5691,8 @@ function searchForm(params) {
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(
field2(t("filter.kind"), select("kind", get("kind"), [["", t("filter.any")], ["rent", t("kind.rent")], ["sale", t("kind.sale")]])),
field2(
t("filter.category"),
select("category", get("category"), [
["", t("filter.any")],
@@ -5148,14 +5702,14 @@ function searchForm(params) {
["commercial", t("cat.commercial")]
])
),
field(
field2(
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") })),
field2(t("filter.maxPrice"), h("input", { name: "max_price", type: "number", min: 0, step: 50, inputmode: "decimal", value: get("max_price") })),
field2(t("filter.minArea"), h("input", { name: "min_area", type: "number", min: 0, step: 5, value: get("min_area") })),
field2(t("filter.minRooms"), h("input", { name: "min_rooms", type: "number", min: 0, step: 0.5, value: get("min_rooms") })),
h(
"div",
{ class: "actions" },
@@ -5240,9 +5794,9 @@ async function loadResults(gen, q, root) {
}
function showSearch(params) {
const gen = state.generation;
clear(app3);
clear(app4);
const results = h("div", { class: "results", "aria-live": "polite" });
app3.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
app4.append(h("p", { class: "tagline" }, t("app.tagline")), 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")));
@@ -5327,9 +5881,9 @@ function listingBody(l) {
}
async function showDetail(author, id) {
const gen = state.generation;
clear(app3);
clear(app4);
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
app3.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
app4.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
let raw;
try {
raw = await getListing(author, id);
@@ -5374,6 +5928,7 @@ function route() {
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) {
setToken(login[1]);
@@ -5382,6 +5937,8 @@ 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/new") void showPublish();
else if (edit) void showPublish(edit[1]);
else if (own) void showOwner(own[1], own[2]);
else showSearch(params);
renderNav();
+15
View File
@@ -323,3 +323,18 @@ label.check { flex-direction: row; align-items: center; gap: 8px; }
.backdrop { align-items: center; }
.sheet { border-radius: var(--radius); }
}
/* Publish form */
.form { display: grid; gap: 14px; max-width: 44rem; }
.form .field label { display: flex; flex-direction: column; gap: 4px; font-size: 0.9rem; font-weight: 600; }
.form .field p { margin: 0; }
.form input:not([type="radio"]):not([type="checkbox"]), .form select, .form textarea { width: 100%; font-weight: 400; }
.form input[aria-invalid="true"], .form select[aria-invalid="true"], .form textarea[aria-invalid="true"] { border-color: var(--bad); }
fieldset.field { border: 0; padding: 0; margin: 0; }
fieldset.field legend { padding: 0; font-size: 0.9rem; font-weight: 600; }
.radios { display: flex; gap: 20px; flex-wrap: wrap; }
.radios label.check { flex-direction: row; font-weight: 400; }
.grid2, .grid3 { display: grid; gap: 12px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
@media (min-width: 40rem) { .grid3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
.listing-bar { margin-bottom: 10px; }
.listing-bar .actions { align-items: center; flex-wrap: wrap; }
+40
View File
@@ -0,0 +1,40 @@
// What the owner sends to publish or change a listing (POST/PUT /api/v1/listings).
// The node adds identity, time, proof-of-work and signature.
import type { Listing } from "./verify.ts";
/** Listings expire after at most this many days (the protocol's limit). */
export const MAX_LIFETIME_DAYS = 30;
export interface Draft {
kind: string;
category: string;
geohash: string;
price: { amount_cents: number; currency: "EUR"; period: "month" | "once" };
area_m2: number;
rooms_x2: number;
features: string[];
title: string;
description: string;
delegate?: string;
expires_in_days: number;
}
/** The draft that reproduces a published listing, valid for a fresh term of `days`. */
export function draftFromListing(l: Listing, days = MAX_LIFETIME_DAYS): Draft {
const period = l.price?.period === "once" ? "once" : "month";
const d: Draft = {
kind: l.kind ?? "",
category: l.category ?? "",
geohash: l.geohash,
price: { amount_cents: l.price?.amount_cents ?? 0, currency: "EUR", period },
area_m2: l.area_m2 ?? 0,
rooms_x2: l.rooms_x2 ?? 0,
features: l.features ?? [],
title: l.title ?? "",
description: l.description ?? "",
expires_in_days: days,
};
if (l.delegate) d.delegate = l.delegate;
return d;
}
+64
View File
@@ -33,3 +33,67 @@ export function decodeGeohash(hash: string): Area | null {
lonErr: (lon[1] - lon[0]) / 2,
};
}
/** Encodes a position as a geohash of `precision` characters (6 is about 1.2 km by 0.6 km). */
export function encodeGeohash(lat: number, lon: number, precision = 6): string {
let latR: [number, number] = [-90, 90];
let lonR: [number, number] = [-180, 180];
let out = "";
let bits = 0;
let value = 0;
let evenBit = true;
while (out.length < precision) {
const range = evenBit ? lonR : latR;
const x = evenBit ? lon : lat;
const mid = (range[0] + range[1]) / 2;
value <<= 1;
if (x >= mid) {
value |= 1;
range[0] = mid;
} else {
range[1] = mid;
}
evenBit = !evenBit;
if (++bits === 5) {
out += ALPHABET[value];
bits = 0;
value = 0;
}
}
return out;
}
const NUM = String.raw`[-+]?\d{1,3}(?:\.\d+)?`;
/**
* Reads a position out of what people copy from a map: "53.5511, 9.9937",
* "53,5511; 9,9937", "53.5511 9.9937", or a link from OpenStreetMap or Google
* Maps. Returns null if there is no valid latitude/longitude pair in it.
*/
export function parseCoordinates(input: string): { lat: number; lon: number } | null {
const s = input.trim();
let a: string | undefined;
let b: string | undefined;
let m: RegExpExecArray | null;
if ((m = new RegExp(String.raw`#map=\d+/(${NUM})/(${NUM})`).exec(s))) [, a, b] = m; // openstreetmap.org
else if ((m = new RegExp(String.raw`mlat=(${NUM})&(?:amp;)?mlon=(${NUM})`).exec(s))) [, a, b] = m;
else if ((m = new RegExp(String.raw`@(${NUM}),(${NUM})`).exec(s))) [, a, b] = m; // google.com/maps
else if ((m = new RegExp(String.raw`^(${NUM})\s*[,;]\s*(${NUM})$`).exec(s))) [, a, b] = m;
else if ((m = /^([-+]?\d{1,3},\d+)\s*;\s*([-+]?\d{1,3},\d+)$/.exec(s))) [, a, b] = m.map((x) => x?.replace(",", ".")); // 53,55; 9,99
else if ((m = /^([-+]?\d{1,3}[.,]\d+)\s+([-+]?\d{1,3}[.,]\d+)$/.exec(s))) [, a, b] = m.map((x) => x?.replace(",", "."));
if (a === undefined || b === undefined) return null;
const lat = Number(a);
const lon = Number(b);
if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
return { lat, lon };
}
/** The size of a geohash cell in metres, for showing how coarse a published location is. */
export function cellMetres(hash: string): { width: number; height: number } | null {
const a = decodeGeohash(hash);
if (!a) return null;
return {
height: Math.round(a.latErr * 2 * 111_320),
width: Math.round(a.lonErr * 2 * 111_320 * Math.cos((a.lat * Math.PI) / 180)),
};
}
+94
View File
@@ -181,6 +181,53 @@ const de = {
"own.needAddress": "Bitte gib eine Adresse ein.",
"own.loadError": "Konnte nicht geladen werden.",
"own.err": "Fehlgeschlagen: {detail}",
"own.new": "Neue Anzeige",
"own.edit": "Bearbeiten",
"own.renew": "Verlängern",
"own.renewing": "Wird verlängert …",
"own.deleteListing": "Anzeige löschen",
"own.deleteListingSure":
"Wirklich löschen? Die Anzeige verschwindet aus dem Netz, und Interessenten können dich darüber nicht mehr erreichen.",
"own.daysLeft": "Noch {n} Tage",
"own.dayLeft": "Noch 1 Tag",
"own.expired": "Abgelaufen",
"own.soon": "Läuft bald ab. „Verlängern“ stellt sie für 30 Tage neu ein.",
"pub.createTitle": "Anzeige veröffentlichen",
"pub.editTitle": "Anzeige bearbeiten",
"pub.intro":
"Deine Anzeige wird signiert und an die Knoten deiner Region verteilt. Name, genaue Adresse und Kontaktdaten stehen nie darin.",
"pub.back": "← Zurück",
"pub.title": "Titel",
"pub.description": "Beschreibung",
"pub.priceRent": "Miete pro Monat (€)",
"pub.priceSale": "Kaufpreis (€)",
"pub.area": "Fläche in m² (optional)",
"pub.rooms": "Zimmer (optional, halbe Zimmer möglich)",
"pub.features": "Ausstattung (optional, mit Komma getrennt)",
"pub.location": "Lage",
"pub.locationHelp":
"Füge Koordinaten ein, zum Beispiel 53.5511, 9.9937 (in OpenStreetMap oder deiner Karten-App den Ort anklicken und kopieren; ein Link geht auch). Veröffentlicht wird nur ein Gebiet von etwa einem Kilometer, nie die genaue Adresse.",
"pub.useLocation": "Meinen Standort verwenden",
"pub.locationShown": "Veröffentlicht wird ein Gebiet von etwa {w} × {h} m um {lat}, {lon} (Code {hash}).",
"pub.duration": "Sichtbar für",
"pub.addrTitle": "Genaue Adresse (optional)",
"pub.addrHelp":
"Bleibt auf deinem Knoten und wird nie veröffentlicht. Du gibst sie später einzelnen Interessenten frei.",
"pub.publish": "Veröffentlichen",
"pub.save": "Änderungen speichern",
"pub.working": "Wird veröffentlicht … (eine kleine Rechenaufgabe, ein paar Sekunden)",
"pub.notFound": "Diese Anzeige gibt es nicht (mehr).",
"pub.eTitle": "Bitte gib einen Titel an (höchstens 120 Zeichen, eine Zeile).",
"pub.eDescription": "Die Beschreibung ist zu lang (höchstens 4000 Zeichen) oder enthält unerlaubte Zeichen.",
"pub.ePrice": "Bitte gib einen Betrag größer als 0 an, zum Beispiel 1150 oder 1.150,50.",
"pub.eArea": "Die Fläche muss eine ganze Zahl sein (höchstens 100000).",
"pub.eRooms": "Zimmer: eine Zahl in halben Schritten, zum Beispiel 2,5.",
"pub.eFeatures": "Höchstens 20 Merkmale mit je höchstens 40 Zeichen.",
"pub.eLocation": "Die Koordinaten konnten nicht gelesen werden. Beispiel: 53.5511, 9.9937",
"pub.eRegion":
"Dein Knoten folgt der Region {region} nicht, du würdest also keine Nachrichten zu dieser Anzeige erhalten. Starte den Knoten mit --region {region} oder wähle einen Ort in {regions}.",
"pub.eRegionEdit": "Die Region einer Anzeige lässt sich nicht ändern. Lösche sie und lege eine neue an.",
"pub.eAddress": "Die Adresse ist zu lang (höchstens 300 Bytes).",
"verify.title": "Prüfung in deinem Browser",
"verify.intro":
"Diese Prüfung läuft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt fälschen.",
@@ -380,6 +427,53 @@ const en: Record<keyof typeof de, string> = {
"own.needAddress": "Please enter an address.",
"own.loadError": "Could not be loaded.",
"own.err": "Failed: {detail}",
"own.new": "New listing",
"own.edit": "Edit",
"own.renew": "Renew",
"own.renewing": "Renewing …",
"own.deleteListing": "Delete listing",
"own.deleteListingSure":
"Really delete? The listing disappears from the network, and people can no longer reach you through it.",
"own.daysLeft": "{n} days left",
"own.dayLeft": "1 day left",
"own.expired": "Expired",
"own.soon": "Expires soon. \"Renew\" publishes it again for 30 days.",
"pub.createTitle": "Publish a listing",
"pub.editTitle": "Edit listing",
"pub.intro":
"Your listing is signed and spread to the nodes of your region. It never contains your name, exact address or contact details.",
"pub.back": "← Back",
"pub.title": "Title",
"pub.description": "Description",
"pub.priceRent": "Rent per month (€)",
"pub.priceSale": "Price (€)",
"pub.area": "Area in m² (optional)",
"pub.rooms": "Rooms (optional, half rooms allowed)",
"pub.features": "Features (optional, separated by commas)",
"pub.location": "Location",
"pub.locationHelp":
"Paste coordinates, for example 53.5511, 9.9937 (click the place in OpenStreetMap or your map app and copy; a link works too). Only an area of about a kilometre is published, never the exact address.",
"pub.useLocation": "Use my location",
"pub.locationShown": "An area of about {w} × {h} m around {lat}, {lon} will be published (code {hash}).",
"pub.duration": "Visible for",
"pub.addrTitle": "Exact address (optional)",
"pub.addrHelp":
"Stays on your node and is never published. You release it to individual people later.",
"pub.publish": "Publish",
"pub.save": "Save changes",
"pub.working": "Publishing … (a small puzzle, a few seconds)",
"pub.notFound": "This listing does not exist (any more).",
"pub.eTitle": "Please enter a title (at most 120 characters, one line).",
"pub.eDescription": "The description is too long (at most 4000 characters) or contains characters that are not allowed.",
"pub.ePrice": "Please enter an amount above 0, for example 1150 or 1,150.50.",
"pub.eArea": "The area must be a whole number (at most 100000).",
"pub.eRooms": "Rooms: a number in half steps, for example 2.5.",
"pub.eFeatures": "At most 20 features of at most 40 characters each.",
"pub.eLocation": "The coordinates could not be read. Example: 53.5511, 9.9937",
"pub.eRegion":
"Your node does not follow region {region}, so you would not receive messages about this listing. Start the node with --region {region} or choose a place in {regions}.",
"pub.eRegionEdit": "A listing's region cannot change. Delete it and create a new one.",
"pub.eAddress": "The address is too long (at most 300 bytes).",
"verify.title": "Checked in your browser",
"verify.intro":
"This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
+4
View File
@@ -6,6 +6,7 @@ import { lang, t, type Key } from "./i18n.ts";
import { contactPanel, showConversation, showInbox } from "./chat.ts";
import { showOwner } from "./owner.ts";
import { getToken, setToken } from "./ownerApi.ts";
import { showPublish } from "./publish.ts";
import { state, verifyOpts } from "./state.ts";
import { verifyListing, type Listing, type Verdict } from "./verify.ts";
@@ -346,6 +347,7 @@ function route(): void {
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.
@@ -355,6 +357,8 @@ 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/new") void showPublish();
else if (edit) void showPublish(edit[1]);
else if (own) void showOwner(own[1], own[2]);
else showSearch(params);
renderNav();
+90
View File
@@ -88,6 +88,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
"section",
{ class: "pane pane-listings" },
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("button", { type: "button", class: "btn", onclick: logout }, t("own.logout"))),
);
@@ -97,6 +98,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
const chips = h("div", { class: "chips-row" });
const reqBox = h("div", { class: "olist" });
const addr = listingId ? addressCard(listingId, () => void refresh()) : null;
const bar = listingId ? listingBar(listingId, () => void refresh()) : null;
const requestsPane = h("section", { class: "pane pane-requests" });
append(
requestsPane,
@@ -104,6 +106,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
? [
h("a", { class: "back narrow-only", href: "#/mine" }, t("own.backListings")),
reqTitle,
bar!.root,
addr!.root,
chips,
reqBox,
@@ -161,6 +164,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
m.address_saved
? h("span", { class: "badge ok" }, t("own.addressSaved"))
: h("span", { class: "badge warn" }, t("own.noAddress")),
lifetimeBadge(m.expires_at),
),
),
);
@@ -195,6 +199,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
function renderRequests(): void {
const m = mine.find((x) => x.id === listingId);
reqTitle.textContent = m?.title ?? "";
bar?.update(m);
const counts = { all: threads.length, reply: threads.filter((x) => x.needs_reply).length, hidden: threads.filter((x) => x.hidden > 0).length };
clear(chips);
for (const [f, key] of [["all", "own.filterAll"], ["reply", "own.filterReply"], ["hidden", "own.filterHidden"]] as const) {
@@ -280,6 +285,91 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
// --- pieces ------------------------------------------------------------------------------
const DAY = 86_400;
/** Warn when a listing has fewer days left than this. */
const SOON_DAYS = 5;
const daysLeft = (expiresAt: number) => Math.ceil((expiresAt - nowSeconds()) / DAY);
function lifetimeBadge(expiresAt: number): HTMLElement {
const n = daysLeft(expiresAt);
if (n <= 0) return h("span", { class: "badge bad" }, t("own.expired"));
return h("span", { class: `badge ${n < SOON_DAYS ? "warn" : "muted"}` }, n === 1 ? t("own.dayLeft") : t("own.daysLeft", { n }));
}
/** Edit, renew and delete for one listing, with how long it has left. */
function listingBar(listingId: string, changed: () => void): { root: HTMLElement; update(m: o.Mine | undefined): void } {
const root = h("div", { class: "listing-bar" });
const problem = h("p", { class: "error", role: "alert" });
let current: o.Mine | undefined;
let renewing = false;
function render(): void {
clear(root);
if (!current) return;
const soon = daysLeft(current.expires_at) < SOON_DAYS;
const renew = h("button", { type: "button", class: `btn${soon ? " primary" : ""}`, onclick: () => void doRenew(renew) }, t("own.renew"));
const del = h("span", null);
const ask = () => {
clear(del);
append(del, [
t("own.deleteListingSure"),
" ",
h(
"button",
{
type: "button",
class: "btn",
onclick: () =>
void o
.deleteListing(listingId)
.then(() => { location.hash = "#/mine"; })
.catch((e) => { problem.textContent = e instanceof o.Unauthorized ? t("own.loginBad") : explain(e); }),
},
t("own.deleteYes"),
),
]);
};
del.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.deleteListing")));
append(root, [
h("p", { class: "badges" }, lifetimeBadge(current.expires_at)),
soon && h("p", { class: "note warn" }, t("own.soon")),
h("div", { class: "actions" }, h("a", { class: "btn", href: `#/mine/${listingId}/edit` }, t("own.edit")), renew, del),
problem,
]);
}
async function doRenew(button: HTMLButtonElement): Promise<void> {
if (renewing) return;
renewing = true;
problem.textContent = "";
button.disabled = true;
button.textContent = t("own.renewing");
try {
const author = state.node?.author;
if (!author) throw new Error("node unknown");
await o.renewListing(author, listingId);
changed();
} catch (e) {
problem.textContent = e instanceof o.Unauthorized ? t("own.loginBad") : explain(e);
button.disabled = false;
button.textContent = t("own.renew");
} finally {
renewing = false;
}
}
return {
root,
update(m) {
// Re-render only when something changed, so a pending confirmation is not wiped by a refresh.
if (m?.expires_at === current?.expires_at && root.firstChild) return;
current = m;
render();
},
};
}
// Words that suggest the buyer wants to know where the place is, in German and
// English. A guess, so it only ever produces a suggestion, never an action.
const ASKS_ADDRESS = /adress|address|anschrift|wo genau|wo liegt|wo befindet|which street|what street|where exactly|where is|where in/i;
+30 -1
View File
@@ -5,7 +5,9 @@
// in sessionStorage only, so closing the tab signs the owner out, and it is only
// ever sent to the node that served this page.
import { HttpError } from "./api.ts";
import { HttpError, getListing } from "./api.ts";
import { MAX_LIFETIME_DAYS, draftFromListing, type Draft } from "./draft.ts";
import type { Listing } from "./verify.ts";
const TOKEN_KEY = "allmende.owner.token";
let memory: string | null = null;
@@ -172,3 +174,30 @@ export async function putAddress(listing: string, a: Address): Promise<void> {
export async function deleteAddress(listing: string): Promise<void> {
await call("DELETE", `/api/v1/listings/${e(listing)}/address`);
}
/** Publishes a new listing. The node signs it and mines its proof-of-work, which takes a few seconds. */
export async function createListing(d: Draft): Promise<Listing> {
return (await call("POST", "/api/v1/listings", d)) as Listing;
}
/** Replaces one of your listings (a new version of it). The region cannot change. */
export async function updateListing(id: string, d: Draft): Promise<Listing> {
return (await call("PUT", `/api/v1/listings/${e(id)}`, d)) as Listing;
}
/** Withdraws a listing: publishes a deletion marker that outlives every older copy. */
export async function deleteListing(id: string): Promise<void> {
await call("DELETE", `/api/v1/listings/${e(id)}`);
}
/** Your own listing as the node has it, or null if it is gone. */
export async function getOwnListing(author: string, id: string): Promise<Listing | null> {
return (await getListing(author, id)) as Listing | null;
}
/** Publishes the listing again for a fresh term, otherwise unchanged. */
export async function renewListing(author: string, id: string, days = MAX_LIFETIME_DAYS): Promise<Listing> {
const l = await getOwnListing(author, id);
if (!l || l.tombstone) throw new HttpError(404, "no such listing of yours");
return updateListing(id, draftFromListing(l, days));
}
+47
View File
@@ -0,0 +1,47 @@
// Reading numbers the way people type them. Pure functions, no browser needed.
/**
* Reads a euro amount typed by a person into cents. Accepts "1150", "1.150,50",
* "1,150.50", "1150.5" and "€ 1 150". "1.150" counts as one thousand one hundred
* fifty (a thousands separator), since nobody rents for 1.15 euros. Null if it
* is not a positive amount with at most two decimals.
*/
export function parseEuros(input: string): number | null {
const s = input.replace(/[€\s ]|eur/gi, "");
if (!/^\d[\d.,]*$/.test(s)) return null;
const lastDot = s.lastIndexOf(".");
const lastComma = s.lastIndexOf(",");
let whole: string;
let frac = "";
if (lastDot >= 0 && lastComma >= 0) {
const at = Math.max(lastDot, lastComma);
whole = s.slice(0, at);
frac = s.slice(at + 1);
} else if (lastDot >= 0 || lastComma >= 0) {
const sep = lastDot >= 0 ? "." : ",";
const parts = s.split(sep);
const last = parts[parts.length - 1]!;
// Several separators, or exactly three digits after one: thousands grouping.
if (parts.length > 2 || last.length === 3) {
whole = parts.join("");
} else {
whole = parts.slice(0, -1).join("");
frac = last;
}
} else {
whole = s;
}
whole = whole.replace(/[.,]/g, "");
if (!/^\d+$/.test(whole) || (frac !== "" && !/^\d{1,2}$/.test(frac))) return null;
const cents = Number(whole) * 100 + Number(frac.padEnd(2, "0") || "0");
return Number.isSafeInteger(cents) && cents > 0 ? cents : null;
}
/** Reads a room count in half steps ("2", "2.5", "2,5") as rooms*2; null if it is not one. */
export function parseRoomsX2(input: string): number | null {
const s = input.trim().replace(",", ".");
if (s === "") return null; // Number("") is 0, which would read as "no rooms"
const n = Number(s);
if (!Number.isFinite(n) || n < 0 || n > 100 || !Number.isInteger(n * 2)) return null;
return n * 2;
}
+328
View File
@@ -0,0 +1,328 @@
// The form to publish a listing, or to change one of yours.
//
// A listing carries no name, address or contact details. The location is
// entered as coordinates copied from any map and published only as a geohash
// cell of about a kilometre. The exact address is optional and stays on this
// node; it is saved apart from the listing and released to individuals later.
import { HttpError } from "./api.ts";
import { append, clear, h } from "./dom.ts";
import { MAX_LIFETIME_DAYS, type Draft } from "./draft.ts";
import { lang, t, type Key } from "./i18n.ts";
import { cellMetres, decodeGeohash, encodeGeohash, parseCoordinates } from "./geohash.ts";
import { renderLogin } from "./owner.ts";
import * as o from "./ownerApi.ts";
import { parseEuros, parseRoomsX2 } from "./parse.ts";
import { state } from "./state.ts";
import type { Listing } from "./verify.ts";
const app = () => document.getElementById("app")!;
const DURATIONS = [7, 14, 21, MAX_LIFETIME_DAYS];
const KINDS = ["rent", "sale"] as const;
const CATEGORIES = ["apartment", "house", "room", "commercial"] as const;
// The limits the node enforces (internal/listing), counted the same way: characters, not bytes.
const MAX_TITLE = 120;
const MAX_DESCRIPTION = 4000;
const MAX_FEATURES = 20;
const MAX_FEATURE = 40;
const MAX_AREA = 100_000;
const MAX_ADDRESS_BYTES = 300; // the saved address is counted in bytes
const chars = (s: string) => [...s].length;
const bytes = (s: string) => new TextEncoder().encode(s).length;
/** Control characters other than a line break. */
const hasControl = (s: string, newlines: boolean) => (newlines ? /[\p{Cc}]/u.test(s.replace(/\n/g, "")) : /\p{Cc}/u.test(s));
function explain(e: unknown): string {
return t("own.err", { detail: e instanceof HttpError ? e.detail : e instanceof Error ? e.message : "?" });
}
interface Field {
root: HTMLElement;
control: HTMLElement;
error(msg: string | null): void;
}
/** A labelled control with room for an error message below it. */
function field(label: string, control: HTMLElement, help?: string): Field {
const err = h("p", { class: "error", role: "alert" });
const root = h("div", { class: "field" }, h("label", null, label, control), help && h("p", { class: "muted small" }, help), err);
return {
root,
control,
error(msg) {
err.textContent = msg ?? "";
if (msg) control.setAttribute("aria-invalid", "true");
else control.removeAttribute("aria-invalid");
},
};
}
const euros = (cents: number) =>
(cents / 100).toLocaleString(lang, { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2, useGrouping: false });
export async function showPublish(editId?: string): Promise<void> {
const gen = state.generation;
if (!o.getToken()) {
renderLogin(false);
return;
}
const root = app();
document.body.classList.remove("wide");
clear(root);
// Changing a listing starts from what is published now.
let old: Listing | null = null;
if (editId) {
root.append(h("p", { class: "muted" }, t("results.loading")));
try {
const author = state.node?.author;
if (!author) throw new Error("node unknown");
old = await o.getOwnListing(author, editId);
} catch (e) {
if (gen !== state.generation) return;
clear(root);
root.append(h("p", { class: "error" }, t("own.loadError")));
return;
}
if (gen !== state.generation) return;
clear(root);
if (!old || old.tombstone) {
root.append(h("a", { class: "back", href: "#/mine" }, t("pub.back")), h("p", { class: "muted" }, t("pub.notFound")));
return;
}
}
// --- the controls
const radios = KINDS.map((k) => h("input", { type: "radio", name: "kind", value: k, checked: (old?.kind ?? "rent") === k }));
const kindField = h(
"fieldset",
{ class: "field" },
h("legend", null, t("filter.kind")),
h("div", { class: "radios" }, ...radios.map((r) => h("label", { class: "check" }, r, " ", t(`kind.${r.value}` as Key)))),
);
const kind = () => (radios.find((r) => r.checked)?.value ?? "rent") as (typeof KINDS)[number];
const category = field(
t("filter.category"),
h("select", { name: "category" }, ...CATEGORIES.map((c) => h("option", { value: c, selected: (old?.category ?? "apartment") === c }, t(`cat.${c}` as Key)))),
);
const title = field(t("pub.title"), h("input", { name: "title", maxlength: MAX_TITLE * 2, value: old?.title ?? "", autocomplete: "off" }));
const description = field(t("pub.description"), h("textarea", { name: "description", rows: 7 }, old?.description ?? ""));
const priceLabel = h("span", null, t("pub.priceRent"));
const priceInput = h("input", { name: "price", inputmode: "decimal", value: old?.price ? euros(old.price.amount_cents) : "", autocomplete: "off" });
const price = field("", priceInput);
price.root.querySelector("label")!.prepend(priceLabel);
const area = field(t("pub.area"), h("input", { name: "area", inputmode: "numeric", value: old?.area_m2 ? String(old.area_m2) : "" }));
const rooms = field(t("pub.rooms"), h("input", { name: "rooms", inputmode: "decimal", value: old?.rooms_x2 ? (old.rooms_x2 / 2).toLocaleString(lang) : "" }));
const features = field(t("pub.features"), h("input", { name: "features", value: (old?.features ?? []).join(", "), autocomplete: "off" }));
const syncKind = () => {
priceLabel.textContent = t(kind() === "rent" ? "pub.priceRent" : "pub.priceSale");
};
for (const r of radios) r.addEventListener("change", syncKind);
// location
const here = old ? decodeGeohash(old.geohash) : null;
const locInput = h("input", {
name: "location",
inputmode: "decimal",
autocomplete: "off",
spellcheck: "false",
placeholder: "53.5511, 9.9937",
value: here ? `${here.lat.toFixed(5)}, ${here.lon.toFixed(5)}` : "",
});
const location_ = field(t("pub.location"), locInput, t("pub.locationHelp"));
const locPreview = h("p", { class: "muted small", "aria-live": "polite" });
const showLocation = () => {
clear(locPreview);
const pos = parseCoordinates(locInput.value);
if (!pos) return;
const g = encodeGeohash(pos.lat, pos.lon);
const c = cellMetres(g);
const a = decodeGeohash(g)!;
append(locPreview, [
t("pub.locationShown", { w: c?.width ?? 0, h: c?.height ?? 0, lat: a.lat.toFixed(3), lon: a.lon.toFixed(3), hash: g }),
" ",
h(
"a",
{
href: `https://www.openstreetmap.org/?mlat=${a.lat.toFixed(5)}&mlon=${a.lon.toFixed(5)}#map=15/${a.lat.toFixed(5)}/${a.lon.toFixed(5)}`,
target: "_blank",
rel: "noopener noreferrer",
},
t("detail.map"),
),
]);
};
locInput.addEventListener("input", showLocation);
showLocation();
const locate =
typeof navigator !== "undefined" && navigator.geolocation && window.isSecureContext
? h(
"button",
{
type: "button",
class: "btn",
onclick: () =>
navigator.geolocation.getCurrentPosition((p) => {
locInput.value = `${p.coords.latitude.toFixed(5)}, ${p.coords.longitude.toFixed(5)}`;
showLocation();
}),
},
t("pub.useLocation"),
)
: null;
const duration = field(
t("pub.duration"),
h("select", { name: "days" }, ...DURATIONS.map((d) => h("option", { value: String(d), selected: d === MAX_LIFETIME_DAYS }, t("own.days", { n: d })))),
);
// the exact address, only when creating: later it is edited where requests are handled
const addr = field(t("own.fAddress"), h("input", { name: "address", autocomplete: "off" }));
const phone = field(t("own.fPhone"), h("input", { name: "phone", maxlength: 40, autocomplete: "off" }));
const email = field(t("own.fEmail"), h("input", { name: "email", type: "email", maxlength: 120, autocomplete: "off" }));
const formError = h("p", { class: "error", role: "alert" });
const submit = h("button", { type: "submit", class: "btn primary" }, t(editId ? "pub.save" : "pub.publish"));
let busy = false;
// --- reading the form
/** Collects errors per field; returns the draft only if there are none. */
function read(): { draft: Draft; address?: o.Address } | null {
const fields: Field[] = [title, description, price, area, rooms, features, location_, addr];
for (const f of fields) f.error(null);
const bad: Array<[Field, string]> = [];
const val = (el: HTMLElement) => (el as HTMLInputElement).value;
const titleText = val(title.control).trim();
if (!titleText || chars(titleText) > MAX_TITLE || hasControl(titleText, false)) bad.push([title, t("pub.eTitle")]);
const desc = val(description.control).replace(/\r\n?/g, "\n").trim();
if (chars(desc) > MAX_DESCRIPTION || hasControl(desc, true)) bad.push([description, t("pub.eDescription")]);
const cents = parseEuros(val(price.control));
if (cents === null) bad.push([price, t("pub.ePrice")]);
const areaText = val(area.control).trim();
const areaM2 = areaText === "" ? 0 : /^\d+$/.test(areaText) ? Number(areaText) : -1;
if (areaM2 < 0 || areaM2 > MAX_AREA) bad.push([area, t("pub.eArea")]);
const roomsText = val(rooms.control).trim();
const roomsX2 = roomsText === "" ? 0 : parseRoomsX2(roomsText);
if (roomsX2 === null) bad.push([rooms, t("pub.eRooms")]);
const list = [...new Set(val(features.control).split(/[,\n]/).map((s) => s.trim()).filter(Boolean))];
if (list.length > MAX_FEATURES || list.some((f) => chars(f) > MAX_FEATURE || hasControl(f, false))) bad.push([features, t("pub.eFeatures")]);
let geohash = "";
const pos = parseCoordinates(val(location_.control));
if (!pos) {
bad.push([location_, t("pub.eLocation")]);
} else {
geohash = encodeGeohash(pos.lat, pos.lon);
const region = geohash.slice(0, 3);
const followed = state.node?.regions;
if (old && old.geohash.slice(0, 3) !== region) bad.push([location_, t("pub.eRegionEdit")]);
else if (followed && followed.length > 0 && !followed.includes(region)) {
bad.push([location_, t("pub.eRegion", { region, regions: followed.join(", ") })]);
}
}
const address = val(addr.control).trim();
if (!editId && address && (bytes(address) > MAX_ADDRESS_BYTES || hasControl(address, true))) bad.push([addr, t("pub.eAddress")]);
if (bad.length > 0 || cents === null || roomsX2 === null) {
for (const [f, msg] of bad) f.error(msg);
bad[0]?.[0].control.focus();
return null;
}
const k = kind();
const draft: Draft = {
kind: k,
category: val(category.control),
geohash,
price: { amount_cents: cents, currency: "EUR", period: k === "rent" ? "month" : "once" },
area_m2: areaM2,
rooms_x2: roomsX2,
features: list,
title: titleText,
description: desc,
expires_in_days: Number(val(duration.control)),
};
if (old?.delegate) draft.delegate = old.delegate;
const out: { draft: Draft; address?: o.Address } = { draft };
if (!editId && address) {
out.address = { address, phone: val(phone.control).trim() || undefined, email: val(email.control).trim() || undefined };
}
return out;
}
const form = h(
"form",
{
class: "form",
novalidate: true,
onsubmit: (ev) => {
ev.preventDefault();
if (busy) return;
const r = read();
if (!r) return;
void (async () => {
busy = true;
formError.textContent = "";
submit.disabled = true;
submit.textContent = t("pub.working");
try {
const l = editId ? await o.updateListing(editId, r.draft) : await o.createListing(r.draft);
if (r.address) {
// The listing exists now; if saving the address fails it can be added from the requests screen.
await o.putAddress(l.id, r.address).catch(() => undefined);
}
if (gen === state.generation) location.hash = `#/mine/${l.id}`;
} catch (e) {
if (e instanceof o.Unauthorized) renderLogin(true);
else formError.textContent = explain(e);
submit.disabled = false;
submit.textContent = t(editId ? "pub.save" : "pub.publish");
} finally {
busy = false;
}
})();
},
},
kindField,
category.root,
title.root,
description.root,
h("div", { class: "grid3" }, price.root, area.root, rooms.root),
features.root,
location_.root,
h("div", { class: "actions" }, locate),
locPreview,
duration.root,
!editId &&
h(
"section",
{ class: "panel" },
h("h2", null, t("pub.addrTitle")),
h("p", { class: "muted small" }, t("pub.addrHelp")),
addr.root,
h("div", { class: "grid2" }, phone.root, email.root),
),
formError,
h("div", { class: "actions" }, submit, h("a", { class: "btn", href: editId ? `#/mine/${editId}` : "#/mine" }, t("own.addrCancel"))),
);
append(root, [
h("a", { class: "back", href: editId ? `#/mine/${editId}` : "#/mine" }, t("pub.back")),
h("h1", null, t(editId ? "pub.editTitle" : "pub.createTitle")),
h("p", { class: "muted" }, t("pub.intro")),
form,
]);
syncKind();
}
+15
View File
@@ -323,3 +323,18 @@ label.check { flex-direction: row; align-items: center; gap: 8px; }
.backdrop { align-items: center; }
.sheet { border-radius: var(--radius); }
}
/* Publish form */
.form { display: grid; gap: 14px; max-width: 44rem; }
.form .field label { display: flex; flex-direction: column; gap: 4px; font-size: 0.9rem; font-weight: 600; }
.form .field p { margin: 0; }
.form input:not([type="radio"]):not([type="checkbox"]), .form select, .form textarea { width: 100%; font-weight: 400; }
.form input[aria-invalid="true"], .form select[aria-invalid="true"], .form textarea[aria-invalid="true"] { border-color: var(--bad); }
fieldset.field { border: 0; padding: 0; margin: 0; }
fieldset.field legend { padding: 0; font-size: 0.9rem; font-weight: 600; }
.radios { display: flex; gap: 20px; flex-wrap: wrap; }
.radios label.check { flex-direction: row; font-weight: 400; }
.grid2, .grid3 { display: grid; gap: 12px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
@media (min-width: 40rem) { .grid3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
.listing-bar { margin-bottom: 10px; }
.listing-bar .actions { align-items: center; flex-wrap: wrap; }
+2 -1
View File
@@ -212,7 +212,8 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
res.end(JSON.stringify(body));
};
// The owner's token-protected routes are played by the test, if it sets `owner`.
if (/^\/api\/v1\/(mine|inbox)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
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)) {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
+118
View File
@@ -0,0 +1,118 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { MAX_LIFETIME_DAYS, draftFromListing } from "../src/draft.ts";
import { parseEuros, parseRoomsX2 } from "../src/parse.ts";
import { cellMetres, decodeGeohash, encodeGeohash, parseCoordinates } from "../src/geohash.ts";
import type { Listing } from "../src/verify.ts";
test("geohash encoding matches known vectors", () => {
assert.equal(encodeGeohash(57.64911, 10.40744, 11), "u4pruydqqvj"); // the classic example
assert.equal(encodeGeohash(42.605, -5.603, 5), "ezs42"); // from the geohash specification
assert.equal(encodeGeohash(0, 0, 1), "s");
assert.equal(encodeGeohash(-90, -180, 6), "000000");
assert.equal(encodeGeohash(53.5511, 9.9937).length, 6);
});
test("encoding agrees with the geohash the Go code wrote", () => {
const fx = JSON.parse(readFileSync(new URL("../../internal/listing/testdata/fixture.json", import.meta.url), "utf8")) as { listing: Listing };
const g = fx.listing.geohash;
const area = decodeGeohash(g)!;
assert.equal(encodeGeohash(area.lat, area.lon, g.length), g);
});
test("encode and decode round trip within the cell", () => {
for (const [lat, lon] of [[53.5511, 9.9937], [48.1371, 11.5754], [-33.8688, 151.2093], [89.9, 179.9], [-89.9, -179.9], [0.0001, -0.0001]] as const) {
const g = encodeGeohash(lat, lon);
const a = decodeGeohash(g)!;
assert.ok(Math.abs(a.lat - lat) <= a.latErr, `lat of ${g}`);
assert.ok(Math.abs(a.lon - lon) <= a.lonErr, `lon of ${g}`);
assert.equal(encodeGeohash(a.lat, a.lon), g, "the centre of a cell encodes to the same cell");
}
});
test("a published cell is about a kilometre wide", () => {
const c = cellMetres(encodeGeohash(53.5511, 9.9937))!;
assert.ok(c.height > 500 && c.height < 700, `height ${c.height}`);
assert.ok(c.width > 600 && c.width < 1300, `width ${c.width}`);
assert.equal(cellMetres("!!"), null);
});
test("coordinates are read from what people copy from maps", () => {
const hh = { lat: 53.5511, lon: 9.9937 };
for (const text of [
"53.5511, 9.9937",
"53.5511,9.9937",
" 53.5511 , 9.9937 ",
"53.5511; 9.9937",
"53,5511; 9,9937", // German decimal comma, semicolon between
"53.5511 9.9937",
"53,5511 9,9937",
"https://www.openstreetmap.org/#map=17/53.5511/9.9937",
"https://www.openstreetmap.org/?mlat=53.5511&mlon=9.9937#map=14/53.5511/9.9937",
"https://www.google.com/maps/place/Hamburg/@53.5511,9.9937,15z/data=!3m1",
]) {
assert.deepEqual(parseCoordinates(text), hh, text);
}
assert.deepEqual(parseCoordinates("-33.8688, 151.2093"), { lat: -33.8688, lon: 151.2093 });
assert.deepEqual(parseCoordinates("53, 9"), { lat: 53, lon: 9 });
});
test("things that are not a position are refused", () => {
for (const text of ["", "Hamburg", "53.5511", "91, 10", "10, 181", "53.5511, 9.9937, 12", "a, b", "1e3, 5", "NaN, 1", "53.5511 / 9.9937 / 4", "https://example.org/x"]) {
assert.equal(parseCoordinates(text), null, JSON.stringify(text));
}
});
test("euro amounts are read in German and English notation", () => {
const ok: Record<string, number> = {
"1150": 115000,
"1.150": 115000, // thousands separator
"1,150": 115000,
"1.150,50": 115050,
"1,150.50": 115050,
"1150.5": 115050,
"1150,5": 115050,
"1150.50": 115050,
"€ 1 150": 115000,
"1150 EUR": 115000,
"485.000": 48500000,
"1.485.000,00": 148500000,
"0,5": 50,
"12": 1200,
};
for (const [text, cents] of Object.entries(ok)) assert.equal(parseEuros(text), cents, text);
for (const text of ["", "0", "0,00", "-5", "abc", "1,2,3x", "12.345,678", "1e5", "99999999999999999999"]) {
assert.equal(parseEuros(text), null, JSON.stringify(text));
}
});
test("rooms are read in half steps", () => {
assert.equal(parseRoomsX2("2"), 4);
assert.equal(parseRoomsX2("2.5"), 5);
assert.equal(parseRoomsX2("2,5"), 5);
assert.equal(parseRoomsX2(" 0.5 "), 1);
assert.equal(parseRoomsX2("0"), 0);
for (const bad of ["", "2.3", "-1", "abc", "101", "1/2"]) assert.equal(parseRoomsX2(bad), null, bad);
});
test("a draft reproduces a listing for a fresh term", () => {
const l = {
kind: "rent", category: "apartment", geohash: "u1x0nw",
price: { amount_cents: 115000, currency: "EUR", period: "month" },
area_m2: 62, rooms_x2: 5, features: ["Balkon"], title: "Helle Wohnung", description: "Ruhig.\nSüdseite.",
} as unknown as Listing;
assert.deepEqual(draftFromListing(l), {
kind: "rent", category: "apartment", geohash: "u1x0nw",
price: { amount_cents: 115000, currency: "EUR", period: "month" },
area_m2: 62, rooms_x2: 5, features: ["Balkon"], title: "Helle Wohnung", description: "Ruhig.\nSüdseite.",
expires_in_days: MAX_LIFETIME_DAYS,
});
assert.equal(draftFromListing({ ...l, delegate: "12D3KooWabcdefgh" } as Listing, 7).delegate, "12D3KooWabcdefgh");
assert.equal(draftFromListing(l, 7).expires_in_days, 7);
assert.equal(draftFromListing({ ...l, price: { amount_cents: 1, currency: "EUR", period: "once" } } as Listing).price.period, "once");
// Optional parts default to empty, not undefined: the API takes them as given.
const bare = draftFromListing({ geohash: "u1x0nw", kind: "sale", category: "house", title: "x" } as unknown as Listing);
assert.deepEqual([bare.area_m2, bare.rooms_x2, bare.features, bare.description], [0, 0, [], ""]);
});
+333
View File
@@ -0,0 +1,333 @@
import assert from "node:assert/strict";
import { afterEach, beforeEach, test } from "node:test";
import { encodeGeohash } from "../src/geohash.ts";
import type { Address, Mine } from "../src/ownerApi.ts";
import { NOW, openPage, startGateway, type Gateway, type Page } from "./helpers.ts";
const TOKEN = "cd34".repeat(16);
const AUTHOR = "a".repeat(64); // the stub gateway's /status reports this author
const NEW_ID = "33".repeat(16);
const L1 = "11".repeat(16);
const HAMBURG = "53.5511, 9.9937";
const HAMBURG_CELL = encodeGeohash(53.5511, 9.9937);
/** A listing of this node, as the public API serves it. */
const own = (over: Record<string, unknown> = {}) => ({
v: 1, id: L1, author: AUTHOR, device: "b".repeat(64), seq: 3, created_at: NOW - 86400, expires_at: NOW + 3 * 86400,
kind: "rent", category: "apartment", geohash: HAMBURG_CELL,
price: { amount_cents: 115000, currency: "EUR", period: "month" },
area_m2: 62, rooms_x2: 5, features: ["Balkon", "Aufzug"], title: "Helle Wohnung", description: "Ruhig.\nSüdseite.",
pow: 1, cert: {}, sig: "", ...over,
});
function fakeNode() {
const s = {
calls: [] as { method: string; path: string; body: string; auth: string }[],
address: null as Address | null,
fail: null as { status: number; error: string } | null,
mine: [] as Mine[],
};
const handler: NonNullable<Gateway["owner"]> = (r) => {
s.calls.push({ method: r.method, path: r.path, body: r.body, auth: r.auth });
if (r.auth !== `Bearer ${TOKEN}`) return { status: 401, body: { error: "unauthorized" } };
if (r.method === "POST" && r.path === "/api/v1/listings") {
if (s.fail) return { status: s.fail.status, body: { error: s.fail.error } };
return { status: 200, body: own({ id: NEW_ID, ...JSON.parse(r.body) }) };
}
if (r.method === "PUT" && /^\/api\/v1\/listings\/[0-9a-f]{32}$/.test(r.path)) {
if (s.fail) return { status: s.fail.status, body: { error: s.fail.error } };
return { status: 200, body: own({ ...JSON.parse(r.body) }) };
}
if (r.method === "DELETE" && /^\/api\/v1\/listings\/[0-9a-f]{32}$/.test(r.path)) return { status: 200, body: {} };
if (r.path === "/api/v1/mine") return { status: 200, body: s.mine };
if (r.path === "/api/v1/inbox") return { status: 200, body: [] };
if (/\/address$/.test(r.path)) {
if (r.method === "PUT") { s.address = JSON.parse(r.body) as Address; return { status: 204 }; }
return s.address ? { status: 200, body: s.address } : { status: 404, body: { error: "none" } };
}
return undefined;
};
return { s, handler };
}
let gw: Gateway;
let node: ReturnType<typeof fakeNode>;
let page: Page | undefined;
beforeEach(async () => {
gw = await startGateway({ listings: [own()] });
node = fakeNode();
gw.owner = node.handler;
node.s.mine = [
{ id: L1, title: "Helle Wohnung", kind: "rent", price: { amount_cents: 115000, currency: "EUR", period: "month" }, expires_at: NOW + 3 * 86400, threads: 0, needs_reply: 0, hidden: 0, address_saved: false },
];
});
afterEach(async () => {
page?.close();
page = undefined;
await gw.close();
});
const open = (hash: string) => (page = openPage(gw.url, hash));
const text = () => page!.document.body.textContent ?? "";
const q = <T extends Element = HTMLElement>(sel: string) => page!.document.querySelector<T>(sel);
const qa = (sel: string) => [...page!.document.querySelectorAll(sel)];
const input = (name: string) => q<HTMLInputElement>(`[name="${name}"]`)!;
const button = (label: string) => qa("button").find((b) => b.textContent === label) as HTMLButtonElement | undefined;
const submit = () => q("form.form")!.dispatchEvent(new page!.window.Event("submit", { cancelable: true }));
const writes = (method: string) => node.s.calls.filter((c) => c.method === method && c.path.startsWith("/api/v1/listings") && !c.path.endsWith("/address"));
const set = (name: string, value: string) => { input(name).value = value; input(name).dispatchEvent(new page!.window.Event("input", { bubbles: true })); };
/** Signs in with the login link and opens the new-listing form. */
async function newForm(): Promise<void> {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = "#/mine/new";
await page!.waitFor(() => q("form.form") !== null, "the form");
}
function fillValid(): void {
set("title", "Helle 2,5-Zimmer-Wohnung – Altbau");
set("description", "Ruhige Altbauwohnung.\nBezug ab 1. Februar.");
set("price", "1.150,50");
set("area", "62");
set("rooms", "2,5");
set("features", "Balkon, Aufzug, Balkon ,");
set("location", HAMBURG);
}
test("signed out, the form asks to sign in; signed in, the listings offer a New listing button", async () => {
open("#/mine/new");
await page!.waitFor(() => q('input[name="token"]') !== null, "the sign-in form");
assert.equal(q("form.form"), null);
page!.close();
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
assert.equal(q<HTMLAnchorElement>(".pane-listings a.btn.primary")!.getAttribute("href"), "#/mine/new");
});
test("a valid form publishes the draft, saves the address, and opens the listing", async () => {
await newForm();
assert.match(text(), /Publish a listing/);
fillValid();
set("address", "Musterweg 7, 22765 Hamburg");
set("phone", "+49 40 1234567");
submit();
await page!.waitFor(() => writes("POST").length === 1, "the listing to be sent");
const post = writes("POST")[0]!;
assert.equal(post.auth, `Bearer ${TOKEN}`);
assert.deepEqual(JSON.parse(post.body), {
kind: "rent",
category: "apartment",
geohash: HAMBURG_CELL,
price: { amount_cents: 115050, currency: "EUR", period: "month" },
area_m2: 62,
rooms_x2: 5,
features: ["Balkon", "Aufzug"],
title: "Helle 2,5-Zimmer-Wohnung – Altbau",
description: "Ruhige Altbauwohnung.\nBezug ab 1. Februar.",
expires_in_days: 30,
});
await page!.waitFor(() => page!.window.location.hash === `#/mine/${NEW_ID}`, "navigation to the new listing");
assert.deepEqual(node.s.address, { address: "Musterweg 7, 22765 Hamburg", phone: "+49 40 1234567" });
assert.ok(!post.body.includes("Musterweg"), "the exact address never goes into the listing");
});
test("optional parts may be left empty, and a sale is priced once", async () => {
await newForm();
set("title", "Reihenhaus");
set("price", "485000");
set("location", HAMBURG);
q<HTMLInputElement>('input[name="kind"][value="sale"]')!.checked = true;
q('input[name="kind"][value="sale"]')!.dispatchEvent(new page!.window.Event("change", { bubbles: true }));
q<HTMLSelectElement>('select[name="category"]')!.value = "house";
q<HTMLSelectElement>('select[name="days"]')!.value = "14";
assert.match(q("form.form")!.textContent!, /Price \(€\)/, "the label follows the offer");
submit();
await page!.waitFor(() => writes("POST").length === 1, "the listing");
assert.deepEqual(JSON.parse(writes("POST")[0]!.body), {
kind: "sale", category: "house", geohash: HAMBURG_CELL,
price: { amount_cents: 48500000, currency: "EUR", period: "once" },
area_m2: 0, rooms_x2: 0, features: [], title: "Reihenhaus", description: "", expires_in_days: 14,
});
await page!.waitFor(() => page!.window.location.hash === `#/mine/${NEW_ID}`, "navigation to the new listing");
assert.equal(node.s.calls.filter((c) => c.method === "PUT" && c.path.endsWith("/address")).length, 0, "no address, nothing saved");
});
test("every problem is explained next to its field, and nothing is sent", async () => {
await newForm();
submit();
await page!.waitFor(() => qa(".form .error").some((e) => e.textContent), "errors");
const msgs = () => qa(".form .field .error").map((e) => e.textContent).filter(Boolean);
assert.equal(msgs().length, 3, "title, price and location are required");
assert.match(text(), /enter a title/);
assert.match(text(), /amount above 0/);
assert.match(text(), /coordinates could not be read/);
assert.equal(input("title").getAttribute("aria-invalid"), "true");
assert.equal(writes("POST").length, 0);
set("title", "x".repeat(121));
set("price", "abc");
set("area", "6x");
set("rooms", "2.3");
set("features", Array.from({ length: 21 }, (_, i) => `f${i}`).join(","));
set("description", "a".repeat(4001));
set("location", "Hamburg");
submit();
assert.equal(msgs().length, 7);
assert.match(text(), /whole number/);
assert.match(text(), /half steps/);
assert.match(text(), /At most 20 features/);
assert.match(text(), /description is too long/);
assert.equal(writes("POST").length, 0);
fillValid(); // fixing the fields clears the messages
submit();
await page!.waitFor(() => writes("POST").length === 1, "the listing once it is valid");
assert.equal(msgs().length, 0);
});
test("a place in a region this node does not follow is refused, with the way out", async () => {
await newForm();
fillValid();
set("location", "48.1371, 11.5754"); // Munich
submit();
await page!.waitFor(() => /does not follow region/.test(text()), "the region message");
assert.match(text(), /--region u28/);
assert.match(text(), /choose a place in u1x/);
assert.equal(writes("POST").length, 0);
});
test("the location shows what will be published, and accepts a map link", async () => {
await newForm();
set("location", "https://www.openstreetmap.org/#map=17/53.5511/9.9937");
const preview = () => qa(".form p.muted.small").map((p) => p.textContent).join("|");
assert.match(preview(), new RegExp(`code ${HAMBURG_CELL}`));
assert.match(preview(), /about \d+ × \d+ m/);
const a = q<HTMLAnchorElement>('.form a[href^="https://www.openstreetmap.org/"]')!;
assert.match(a.getAttribute("rel")!, /noopener/);
assert.equal(a.getAttribute("target"), "_blank");
fillValid();
set("location", "https://www.openstreetmap.org/#map=17/53.5511/9.9937");
set("title", "Mit Link eingefügt");
submit();
await page!.waitFor(() => writes("POST").length === 1, "the listing");
assert.equal(JSON.parse(writes("POST")[0]!.body).geohash, HAMBURG_CELL);
});
test("a refusal from the node is shown and the form keeps what was typed", async () => {
await newForm();
fillValid();
node.s.fail = { status: 400, error: "price out of range" };
submit();
await page!.waitFor(() => /Failed: price out of range/.test(text()), "the node's message");
assert.equal(input("title").value, "Helle 2,5-Zimmer-Wohnung – Altbau");
assert.equal(q<HTMLButtonElement>('button[type="submit"]')!.disabled, false, "it can be tried again");
assert.equal(page!.window.location.hash, "#/mine/new");
node.s.fail = null;
submit();
await page!.waitFor(() => page!.window.location.hash === `#/mine/${NEW_ID}`, "a second try works");
});
test("changing a listing starts from what is published, and re-publishes it", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = `#/mine/${L1}/edit`;
await page!.waitFor(() => q("form.form") !== null, "the form");
assert.match(text(), /Edit listing/);
assert.equal(input("title").value, "Helle Wohnung");
assert.equal(input("price").value, "1150");
assert.equal(input("area").value, "62");
assert.equal(input("rooms").value, "2.5");
assert.equal(input("features").value, "Balkon, Aufzug");
assert.match(q<HTMLTextAreaElement>('textarea[name="description"]')!.value, /Ruhig\.\nSüdseite\./);
assert.match(input("location").value, /^53\.\d+, 9\.\d+$/);
assert.equal(q('input[name="address"]'), null, "the address is edited where requests are handled");
set("title", "Helle Wohnung, jetzt renoviert");
set("price", "1200");
submit();
await page!.waitFor(() => writes("PUT").length === 1, "the new version");
const put = writes("PUT")[0]!;
assert.equal(put.path, `/api/v1/listings/${L1}`);
const body = JSON.parse(put.body);
assert.equal(body.title, "Helle Wohnung, jetzt renoviert");
assert.equal(body.price.amount_cents, 120000);
assert.equal(body.geohash, HAMBURG_CELL, "the unchanged location keeps its cell");
assert.deepEqual(body.features, ["Balkon", "Aufzug"]);
await page!.waitFor(() => page!.window.location.hash === `#/mine/${L1}`, "back to the listing");
});
test("the region of an existing listing cannot be changed", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = `#/mine/${L1}/edit`;
await page!.waitFor(() => q("form.form") !== null, "the form");
set("location", "52.52, 13.405"); // Berlin: another region
submit();
await page!.waitFor(() => /region cannot change/.test(text()), "the region message");
assert.equal(writes("PUT").length, 0);
});
test("a listing that does not exist cannot be edited", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = `#/mine/${"99".repeat(16)}/edit`;
await page!.waitFor(() => /does not exist/.test(text()), "the not-found notice");
assert.equal(q("form.form"), null);
});
test("a listing that expires soon is flagged, and Renew publishes it again for 30 days", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
assert.match(qa(".pane-listings .ocard")[0]!.textContent!, /3 days left/);
assert.ok(qa(".pane-listings .ocard .badge.warn").some((b) => /days left/.test(b.textContent!)), "flagged as running out");
page!.window.location.hash = `#/mine/${L1}`;
await page!.waitFor(() => button("Renew") !== undefined, "the Renew button");
assert.match(text(), /Expires soon/);
button("Renew")!.click();
await page!.waitFor(() => writes("PUT").length === 1, "the renewal");
const body = JSON.parse(writes("PUT")[0]!.body);
assert.equal(body.expires_in_days, 30);
assert.equal(body.title, "Helle Wohnung", "nothing else changes");
assert.equal(body.geohash, HAMBURG_CELL);
assert.deepEqual(body.features, ["Balkon", "Aufzug"]);
assert.equal(body.price.period, "month");
});
test("a comfortable listing is not nagged about, and an expired one says so", async () => {
node.s.mine = [{ ...node.s.mine[0]!, expires_at: NOW + 20 * 86400 }];
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
assert.match(qa(".pane-listings .ocard")[0]!.textContent!, /20 days left/);
page!.window.location.hash = `#/mine/${L1}`;
await page!.waitFor(() => button("Renew") !== undefined, "the bar");
assert.doesNotMatch(text(), /Expires soon/);
page!.close();
node.s.mine = [{ ...node.s.mine[0]!, expires_at: NOW - 10 }];
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings again");
assert.match(qa(".pane-listings .ocard")[0]!.textContent!, /Expired/);
});
test("deleting a listing asks first, then withdraws it", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = `#/mine/${L1}`;
await page!.waitFor(() => button("Delete listing") !== undefined, "the delete button");
button("Delete listing")!.click();
assert.match(text(), /people can no longer reach you/);
assert.equal(writes("DELETE").length, 0, "one click deletes nothing");
button("Yes, delete")!.click();
await page!.waitFor(() => writes("DELETE").length === 1, "the deletion");
assert.equal(writes("DELETE")[0]!.path, `/api/v1/listings/${L1}`);
await page!.waitFor(() => page!.window.location.hash === "#/mine", "back to the listings");
});