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:
@@ -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;
|
||||
}
|
||||
@@ -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)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
Reference in New Issue
Block a user