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; }