Add owner inbox UI with address release

Web: "My listings" (listings, requests of a listing, conversation) in
three panes on wide screens and one at a time on phones, and a sheet or
dialog to release the exact address. Sign-in uses a link printed by
`node run` (token in the URL fragment, kept in sessionStorage only).

API: GET /api/v1/mine (own listings with request counts and whether an
address is saved); inbox rows gain last_dir, needs_reply, preview,
effort and grant_until, and can be filtered by listing.

Docs: PROTOCOL.md and README describe the owner UI and login.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 20:02:51 +01:00
co-authored by Claude Sonnet 5.5
parent 3b0351c774
commit 8edae3ae56
17 changed files with 2400 additions and 49 deletions
+745 -36
View File
@@ -197,6 +197,75 @@ var de = {
"inbox.none": "Du hast noch keine Unterhaltungen. \xD6ffne eine Anzeige und schreibe dem Anbieter.",
"inbox.last": "Zuletzt: {date}",
"inbox.note": "Diese Liste liegt nur in diesem Browser.",
"nav.owner": "Meine Anzeigen",
"own.loginTitle": "Anmelden als Anbieter",
"own.loginHelp": "Beim Start gibt dein Knoten im Terminal einen Anmelde-Link aus. \xD6ffne ihn hier, oder f\xFCge den Token (Datei admin.token im Datenordner) ein. Er bleibt nur in diesem Tab gespeichert.",
"own.token": "Token",
"own.login": "Anmelden",
"own.loginBad": "Der Knoten hat den Token abgelehnt.",
"own.logout": "Abmelden",
"own.listings": "Deine Anzeigen",
"own.none": "Dein Knoten hat keine aktiven Anzeigen.",
"own.perMonth": "/ Monat",
"own.needReply": "{n} brauchen eine Antwort",
"own.noRequests": "Keine Anfragen",
"own.allAnswered": "Alle beantwortet",
"own.addressSaved": "Adresse gespeichert",
"own.noAddress": "Keine Adresse gespeichert",
"own.backListings": "\u2190 Anzeigen",
"own.backRequests": "\u2190 Anfragen",
"own.pickListing": "W\xE4hle links eine Anzeige.",
"own.pickRequest": "W\xE4hle eine Anfrage.",
"own.addrTitle": "Adresse auf deinem Knoten",
"own.addrHelp": "Wird nie ver\xF6ffentlicht. Nur Personen, denen du sie freigibst, erhalten sie.",
"own.addrNone": "Noch keine Adresse gespeichert. Ohne sie kannst du keine Adresse freigeben.",
"own.addrChange": "\xC4ndern",
"own.addrAdd": "Adresse hinzuf\xFCgen",
"own.addrSave": "Speichern",
"own.addrRemove": "Entfernen",
"own.addrCancel": "Abbrechen",
"own.fAddress": "Adresse",
"own.fPhone": "Telefon (optional)",
"own.fEmail": "E-Mail (optional)",
"own.requests": "Anfragen",
"own.request": "Anfrage #{id}",
"own.filterAll": "Alle {n}",
"own.filterReply": "Braucht Antwort {n}",
"own.filterHidden": "Link versteckt {n}",
"own.noMatch": "Keine Anfragen in dieser Ansicht.",
"own.stReply": "Braucht Antwort",
"own.stReplied": "Beantwortet",
"own.stHidden": "Link versteckt",
"own.stGrant": "Adresse bis {date}",
"own.stGrantEnded": "Adresse abgelaufen",
"own.effort": "Aufwand {n} Bit",
"own.hiddenPreview": "Ausgeblendet: enth\xE4lt einen Link",
"own.limitNote": "Pro Anzeige zeigt dein Knoten nur eine begrenzte Zahl neuer Anfragen am Tag; der Rest wartet, die mit dem gr\xF6\xDFten Aufwand zuerst.",
"own.buyer": "Interessent",
"own.you": "Du",
"own.anon": "Anonym, Ende-zu-Ende-verschl\xFCsselt",
"own.first": "Erste Nachricht dieser Person. Bis du antwortest, darf sie nur kurzen Text ohne Links schicken. Alles wird als reiner Text angezeigt, nie als Link.",
"own.hiddenMsg": "Ausgeblendet: Eine erste Nachricht muss kurz sein und darf keine Links enthalten.",
"own.grantSent": "Adresse freigegeben bis {date}",
"own.reply": "Antwort",
"own.send": "Senden",
"own.sending": "Wird gesendet \u2026",
"own.release": "Adresse freigeben",
"own.delete": "Unterhaltung l\xF6schen",
"own.deleteSure": "Wirklich l\xF6schen? Sie wird von deinem Knoten entfernt.",
"own.deleteYes": "Ja, l\xF6schen",
"own.sheetTitle": "Adresse freigeben",
"own.sheetHelp": "Eine signierte Nachricht, nur f\xFCr diese Person sichtbar. Ihr Bildschirm blendet sie nach dem Datum aus. Sie k\xF6nnte sie trotzdem kopiert haben.",
"own.fNote": "Hinweis an die Person",
"own.fValid": "Sichtbar f\xFCr",
"own.days": "{n} Tage",
"own.day": "1 Tag",
"own.remember": "Diese Adresse f\xFCr die Anzeige speichern",
"own.sendAddress": "Adresse senden",
"own.close": "Schlie\xDFen",
"own.needAddress": "Bitte gib eine Adresse ein.",
"own.loadError": "Konnte nicht geladen werden.",
"own.err": "Fehlgeschlagen: {detail}",
"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.",
@@ -308,6 +377,75 @@ var en = {
"inbox.none": "You have no conversations yet. Open a listing and write to the owner.",
"inbox.last": "Last activity: {date}",
"inbox.note": "This list is kept only in this browser.",
"nav.owner": "My listings",
"own.loginTitle": "Sign in as owner",
"own.loginHelp": "When it starts, your node prints a sign-in link in the terminal. Open it here, or paste the token (the file admin.token in the data folder). It is kept in this tab only.",
"own.token": "Token",
"own.login": "Sign in",
"own.loginBad": "The node rejected the token.",
"own.logout": "Sign out",
"own.listings": "Your listings",
"own.none": "Your node has no active listings.",
"own.perMonth": "/ month",
"own.needReply": "{n} need a reply",
"own.noRequests": "No requests",
"own.allAnswered": "All answered",
"own.addressSaved": "Address saved",
"own.noAddress": "No address saved",
"own.backListings": "\u2190 Listings",
"own.backRequests": "\u2190 Requests",
"own.pickListing": "Choose a listing on the left.",
"own.pickRequest": "Choose a request.",
"own.addrTitle": "Address on your node",
"own.addrHelp": "Never published. Only people you release it to receive it.",
"own.addrNone": "No address saved yet. Without one you cannot release an address.",
"own.addrChange": "Change",
"own.addrAdd": "Add address",
"own.addrSave": "Save",
"own.addrRemove": "Remove",
"own.addrCancel": "Cancel",
"own.fAddress": "Address",
"own.fPhone": "Phone (optional)",
"own.fEmail": "Email (optional)",
"own.requests": "Requests",
"own.request": "Request #{id}",
"own.filterAll": "All {n}",
"own.filterReply": "Needs reply {n}",
"own.filterHidden": "Link hidden {n}",
"own.noMatch": "No requests in this view.",
"own.stReply": "Needs reply",
"own.stReplied": "Replied",
"own.stHidden": "Link hidden",
"own.stGrant": "Address until {date}",
"own.stGrantEnded": "Address expired",
"own.effort": "Effort {n} bit",
"own.hiddenPreview": "Hidden: contains a link",
"own.limitNote": "Your node shows only a limited number of new requests per listing per day; the rest wait, strongest effort first.",
"own.buyer": "Buyer",
"own.you": "You",
"own.anon": "Anonymous, end-to-end encrypted",
"own.first": "First message from this person. Until you reply they can send short text only, no links. Everything is shown as plain text, never as a link.",
"own.hiddenMsg": "Hidden: a first message must be short and contain no links.",
"own.grantSent": "Address released until {date}",
"own.reply": "Reply",
"own.send": "Send",
"own.sending": "Sending \u2026",
"own.release": "Release address",
"own.delete": "Delete conversation",
"own.deleteSure": "Really delete? It is removed from your node.",
"own.deleteYes": "Yes, delete",
"own.sheetTitle": "Release address",
"own.sheetHelp": "A signed message, visible only to this person. Their screen hides it after the date. They could still have copied it.",
"own.fNote": "Note to the buyer",
"own.fValid": "Visible for",
"own.days": "{n} days",
"own.day": "1 day",
"own.remember": "Save this address for the listing",
"own.sendAddress": "Send address",
"own.close": "Close",
"own.needAddress": "Please enter an address.",
"own.loadError": "Could not be loaded.",
"own.err": "Failed: {detail}",
"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.",
@@ -343,6 +481,13 @@ function rooms(x2) {
function date(unix) {
return new Date(unix * 1e3).toLocaleDateString(lang, { dateStyle: "medium" });
}
function when(unix) {
const d = new Date(unix * 1e3);
if (d.toDateString() === new Date(Date.now()).toDateString()) {
return d.toLocaleTimeString(lang, { hour: "2-digit", minute: "2-digit" });
}
return d.toLocaleDateString(lang, { day: "numeric", month: "short" });
}
function price(l) {
if (!l.price) return "";
const base = money(l.price.amount_cents);
@@ -2799,7 +2944,7 @@ function edwards(params, extraOpts = {}) {
const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
try {
return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
} catch (e) {
} catch (e2) {
return { isValid: false, value: _0n4 };
}
} : opts.uvRatio;
@@ -3786,15 +3931,15 @@ function aead(shared, epk, rpk, header) {
const key = hkdf(sha256, shared, concat(epk, rpk), SEAL_INFO, 32);
return chacha20poly1305(key, new Uint8Array(12), enc2.encode(canonicalize(header)));
}
function headerOf(e) {
function headerOf(e2) {
return {
v: e.v,
listing: { author: e.listing.author, id: e.listing.id },
to: e.to,
rcpt: e.rcpt,
epk: e.epk,
created_at: e.created_at,
expires_at: e.expires_at
v: e2.v,
listing: { author: e2.listing.author, id: e2.listing.id },
to: e2.to,
rcpt: e2.rcpt,
epk: e2.epk,
created_at: e2.created_at,
expires_at: e2.expires_at
};
}
var tick = () => new Promise((r) => setTimeout(r, 0));
@@ -3866,27 +4011,27 @@ var fail = (error) => ({ ok: false, error });
function openReply(input, threadSecret, expect) {
try {
return open(input, threadSecret, expect);
} catch (e) {
return fail(e instanceof Error ? e.message : "unreadable");
} catch (e2) {
return fail(e2 instanceof Error ? e2.message : "unreadable");
}
}
function open(input, threadSecret, expect) {
if (!isObject(input) || !isObject(input.listing)) return fail("not an envelope");
const e = input;
const e2 = input;
const threadPub = threadPublic(threadSecret);
const epk = hexBytes(e.epk, 32);
const ct = typeof e.ct === "string" && /^[0-9a-f]*$/.test(e.ct) && e.ct.length % 2 === 0 ? hexBytes(e.ct, e.ct.length / 2) : null;
if (e.v !== VERSION || e.to !== "buyer" || e.rcpt !== mailbox(threadPub) || !epk || !ct || ct.length < TAG + 1 || ct.length > BUCKETS[BUCKETS.length - 1] + TAG || !safeInt(e.created_at) || !safeInt(e.expires_at)) {
const epk = hexBytes(e2.epk, 32);
const ct = typeof e2.ct === "string" && /^[0-9a-f]*$/.test(e2.ct) && e2.ct.length % 2 === 0 ? hexBytes(e2.ct, e2.ct.length / 2) : null;
if (e2.v !== VERSION || e2.to !== "buyer" || e2.rcpt !== mailbox(threadPub) || !epk || !ct || ct.length < TAG + 1 || ct.length > BUCKETS[BUCKETS.length - 1] + TAG || !safeInt(e2.created_at) || !safeInt(e2.expires_at)) {
return fail("not a reply for this conversation");
}
if (e.listing.author !== expect.author || e.listing.id !== expect.id) {
if (e2.listing.author !== expect.author || e2.listing.id !== expect.id) {
return fail("reply refers to another listing");
}
const rpk = x25519.getPublicKey(threadSecret);
const shared = x25519.getSharedSecret(threadSecret, epk);
let body;
try {
body = unpad(aead(shared, epk, rpk, headerOf(e)).decrypt(ct));
body = unpad(aead(shared, epk, rpk, headerOf(e2)).decrypt(ct));
} catch {
return fail("cannot decrypt");
}
@@ -3897,7 +4042,7 @@ function open(input, threadSecret, expect) {
if (bad) return fail(bad);
const plain = p;
if (plain.thread !== threadPub) return fail("reply belongs to another thread");
if (plain.listing.author !== e.listing.author || plain.listing.id !== e.listing.id) {
if (plain.listing.author !== e2.listing.author || plain.listing.id !== e2.listing.id) {
return fail("reply refers to another listing");
}
const c = plain.cert;
@@ -4030,12 +4175,12 @@ var app = () => document.getElementById("app");
var fromHex = (s) => Uint8Array.from(s.match(/../g) ?? [], (b) => parseInt(b, 16));
var difficulty = () => state.node?.message_difficulty ?? DEFAULT_MESSAGE_DIFFICULTY;
var utf8 = (s) => new TextEncoder().encode(s).length;
function describe(e) {
if (e instanceof InputError) return t(`problem.${e.problem}`);
if (e instanceof HttpError) {
if (e.status === 404) return t("send.404");
if (e.status === 429) return t("send.429");
return t("send.other", { detail: e.detail });
function describe(e2) {
if (e2 instanceof InputError) return t(`problem.${e2.problem}`);
if (e2 instanceof HttpError) {
if (e2.status === 404) return t("send.404");
if (e2.status === 429) return t("send.429");
return t("send.other", { detail: e2.detail });
}
return t("send.network");
}
@@ -4071,8 +4216,8 @@ function composer(opts) {
await opts.send(text);
area.value = "";
update();
} catch (e) {
problem.textContent = describe(e);
} catch (e2) {
problem.textContent = describe(e2);
} finally {
button.disabled = false;
area.disabled = false;
@@ -4248,7 +4393,7 @@ async function showConversation(author, id, secret) {
{ class: "panel" },
h("h2", null, t("chat.link")),
h("p", { class: "muted" }, t("chat.linkHelp")),
h("input", { class: "mono", readonly: true, value: link, "aria-label": t("chat.link"), onfocus: (e) => e.target.select() })
h("input", { class: "mono", readonly: true, value: link, "aria-label": t("chat.link"), onfocus: (e2) => e2.target.select() })
),
deleteControl(conv)
]);
@@ -4375,10 +4520,558 @@ function showInbox() {
]);
}
// src/ownerApi.ts
var TOKEN_KEY = "allmende.owner.token";
var memory = null;
function getToken() {
try {
return sessionStorage.getItem(TOKEN_KEY) ?? memory;
} catch {
return memory;
}
}
function setToken(token) {
memory = token;
try {
sessionStorage.setItem(TOKEN_KEY, token);
} catch {
}
}
function clearToken() {
memory = null;
try {
sessionStorage.removeItem(TOKEN_KEY);
} catch {
}
}
var Unauthorized = class extends Error {
constructor() {
super("unauthorized");
}
};
async function call(method, path, body) {
const token = getToken();
if (!token) throw new Unauthorized();
const res = await fetch(path, {
method,
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
...body === void 0 ? {} : { "Content-Type": "application/json" }
},
body: body === void 0 ? void 0 : JSON.stringify(body)
});
if (res.status === 401) {
clearToken();
throw new Unauthorized();
}
if (res.status === 204) return null;
let data = null;
try {
data = await res.json();
} catch {
}
if (!res.ok) {
const detail = typeof data?.error === "string" ? data.error : res.statusText;
throw new HttpError(res.status, detail);
}
return data;
}
var e = encodeURIComponent;
async function getMine() {
return await call("GET", "/api/v1/mine");
}
async function getThreads(listing) {
return await call("GET", `/api/v1/inbox?listing=${e(listing)}`);
}
async function getMessages(listing, thread) {
return await call("GET", `/api/v1/inbox/${e(listing)}/${e(thread)}`);
}
async function sendReply(listing, thread, r) {
await call("POST", `/api/v1/inbox/${e(listing)}/${e(thread)}`, r);
}
async function deleteThread(listing, thread) {
await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}`);
}
async function getAddress(listing) {
try {
return await call("GET", `/api/v1/listings/${e(listing)}/address`);
} catch (err) {
if (err instanceof HttpError && err.status === 404) return null;
throw err;
}
}
async function putAddress(listing, a) {
await call("PUT", `/api/v1/listings/${e(listing)}/address`, a);
}
async function deleteAddress(listing) {
await call("DELETE", `/api/v1/listings/${e(listing)}/address`);
}
// src/owner.ts
var REFRESH_MS = 3e4;
var VALID_DAYS = [1, 3, 7, 14, 30];
var DEFAULT_DAYS = 7;
var app2 = () => document.getElementById("app");
var shortId = (thread) => thread.slice(-4);
function explain(e2) {
return t("own.err", { detail: e2 instanceof HttpError ? e2.detail : e2 instanceof Error ? e2.message : "?" });
}
function renderLogin(rejected) {
const root = app2();
document.body.classList.remove("wide");
clear(root);
const input = h("input", { type: "password", name: "token", autocomplete: "off", spellcheck: "false", "aria-label": t("own.token"), required: true });
append(root, [
h(
"section",
{ class: "panel" },
h("h1", null, t("own.loginTitle")),
h("p", { class: "muted" }, t("own.loginHelp")),
rejected && h("p", { class: "error", role: "alert" }, t("own.loginBad")),
h(
"form",
{
class: "stack",
onsubmit: (ev) => {
ev.preventDefault();
const v = input.value.trim();
if (!v) return;
setToken(v);
void showOwner();
}
},
h("label", null, t("own.token"), input),
h("div", { class: "actions" }, h("button", { type: "submit", class: "btn primary" }, t("own.login")))
)
)
]);
}
async function showOwner(listingId, thread) {
const gen = state.generation;
if (!getToken()) {
renderLogin(false);
return;
}
const root = app2();
document.body.classList.add("wide");
clear(root);
const depth = thread ? 3 : listingId ? 2 : 1;
let mine2 = [];
let threads = [];
let msgs = [];
let filter = "all";
let loaded2 = false;
const notice = h("p", { class: "error", role: "alert" });
const listingsBox = h("div", { class: "olist" });
const listingsPane = h(
"section",
{ class: "pane pane-listings" },
h("h2", { class: "pane-title" }, t("own.listings")),
listingsBox,
h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout")))
);
const reqTitle = h("h2", { class: "pane-title" });
const chips = h("div", { class: "chips-row" });
const reqBox = h("div", { class: "olist" });
const addr = listingId ? addressCard(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,
addr.root,
chips,
reqBox,
h("p", { class: "muted small" }, t("own.limitNote"))
] : [h("p", { class: "muted pick" }, t("own.pickListing"))]
);
const msgBox = h("div", { class: "thread", "aria-live": "polite" });
const threadHead = h("h2", { class: "pane-title" });
const firstNote = h("p", { class: "note warn" }, t("own.first"));
const threadPane = h("section", { class: "pane pane-thread" });
if (listingId && thread) {
append(threadPane, [
h("a", { class: "back narrow-only", href: `#/mine/${listingId}` }, t("own.backRequests")),
threadHead,
h("p", { class: "muted small" }, t("own.anon")),
msgBox,
firstNote,
composer2(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())),
deleteControl2(listingId, thread)
]);
} else {
threadPane.append(h("p", { class: "muted pick" }, listingId ? t("own.pickRequest") : ""));
}
append(root, [notice, h("div", { class: `owner depth-${depth}` }, listingsPane, requestsPane, threadPane)]);
const kindLabel = (k) => k === "rent" || k === "sale" ? t(`kind.${k}`) : k ?? "";
function renderListings() {
clear(listingsBox);
if (loaded2 && mine2.length === 0) listingsBox.append(h("p", { class: "muted" }, t("own.none")));
for (const m of mine2) {
const sub = [kindLabel(m.kind), m.price ? price({ price: m.price }) : ""].filter(Boolean).join(" \xB7 ");
listingsBox.append(
h(
"a",
{ class: `ocard${m.id === listingId ? " selected" : ""}`, href: `#/mine/${m.id}`, "aria-current": m.id === listingId ? "page" : void 0 },
h("b", null, m.title || m.id.slice(0, 8)),
sub && h("span", { class: "muted small" }, sub),
h(
"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"))
)
)
);
}
}
function status(th) {
const now = nowSeconds();
const out = [];
const allHidden = th.hidden > 0 && th.hidden === th.messages;
if (th.needs_reply) out.push(h("span", { class: "badge warn" }, t("own.stReply")));
if (th.hidden > 0) out.push(h("span", { class: "badge bad" }, t("own.stHidden")));
if (th.grant_until) {
out.push(
th.grant_until > now ? h("span", { class: "badge ok" }, t("own.stGrant", { date: date(th.grant_until) })) : h("span", { class: "badge muted" }, t("own.stGrantEnded"))
);
} else if (th.replied && !th.needs_reply) {
out.push(h("span", { class: "badge muted" }, t("own.stReplied")));
}
if (!out.length && !allHidden) out.push(h("span", { class: "badge muted" }, t("own.stReplied")));
return out;
}
function preview(th) {
if (th.preview) return th.preview;
if (th.last_dir === "in") return t("own.hiddenPreview");
return th.grant_until ? t("own.grantSent", { date: date(th.grant_until) }) : "";
}
function renderRequests() {
const m = mine2.find((x) => x.id === listingId);
reqTitle.textContent = m?.title ?? "";
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"]]) {
chips.append(
h("button", { type: "button", class: `chip${filter === f ? " on" : ""}`, "aria-pressed": filter === f ? "true" : "false", onclick: () => {
filter = f;
renderRequests();
} }, t(key, { n: counts[f] }))
);
}
const shown = threads.filter((x) => filter === "all" || (filter === "reply" ? x.needs_reply : x.hidden > 0));
clear(reqBox);
if (loaded2 && shown.length === 0) reqBox.append(h("p", { class: "muted" }, t("own.noMatch")));
for (const th of shown) {
reqBox.append(
h(
"a",
{ class: `ocard${th.thread === thread ? " selected" : ""}`, href: `#/mine/${th.listing}/${th.thread}`, "aria-current": th.thread === thread ? "page" : void 0 },
h("span", { class: "row" }, h("b", null, t("own.request", { id: shortId(th.thread) })), h("span", { class: "muted small" }, when(th.last_at))),
h("span", { class: th.preview ? "clip" : "clip muted" }, preview(th)),
h("span", { class: "badges" }, ...status(th), h("span", { class: "muted small" }, t("own.effort", { n: th.effort })))
)
);
}
}
function renderThread() {
if (!thread) return;
threadHead.textContent = t("own.request", { id: shortId(thread) });
clear(msgBox);
for (const m of msgs) msgBox.append(bubble2(m));
firstNote.hidden = msgs.some((m) => m.dir === "out");
}
function renderAll() {
renderListings();
if (listingId) renderRequests();
renderThread();
}
function logout() {
clearToken();
location.hash = "#/";
}
async function refresh() {
try {
mine2 = await getMine();
if (listingId) threads = await getThreads(listingId);
if (listingId && thread) {
try {
msgs = await getMessages(listingId, thread);
} catch (e2) {
if (e2 instanceof HttpError && e2.status === 404) {
if (gen === state.generation) location.hash = `#/mine/${listingId}`;
return;
}
throw e2;
}
}
} catch (e2) {
if (gen !== state.generation) return;
if (e2 instanceof Unauthorized) renderLogin(true);
else notice.textContent = t("own.loadError");
return;
}
if (gen !== state.generation) return;
notice.textContent = "";
loaded2 = true;
renderAll();
}
renderListings();
await refresh();
const tick2 = () => {
setTimeout(() => {
if (gen !== state.generation) return;
void refresh().then(tick2);
}, REFRESH_MS);
};
tick2();
}
function bubble2(m) {
const mine2 = m.dir === "out";
const who = mine2 ? t("own.you") : t("own.buyer");
const head = h("div", { class: "who" }, who, " \xB7 ", when(m.sent_at));
if (m.hidden) {
return h("div", { class: "msg in" }, head, h("p", { class: "pre muted" }, t("own.hiddenMsg")));
}
if (m.type === "grant") {
const row = (label2, v) => v ? [h("dt", null, t(label2)), h("dd", { class: "pre" }, v)] : [];
return h(
"div",
{ class: "msg out" },
head,
h(
"div",
{ class: "grant" },
h("strong", null, t("own.grantSent", { date: date(m.valid_until ?? 0) })),
h("dl", { class: "kv" }, ...row("own.fAddress", m.address), ...row("own.fPhone", m.phone), ...row("own.fEmail", m.email), ...row("own.fNote", m.note))
)
);
}
return h("div", { class: `msg ${mine2 ? "out" : "in"}` }, head, h("p", { class: "pre" }, m.text ?? ""));
}
function composer2(listingId, thread, done, release) {
const area = h("textarea", { rows: 3, "aria-label": t("own.reply"), name: "reply" });
const problem = h("p", { class: "error", role: "alert" });
const send = h("button", { type: "submit", class: "btn primary" }, t("own.send"));
const rel = h("button", { type: "button", class: "btn", onclick: () => release(rel) }, t("own.release"));
return h(
"form",
{
class: "compose",
onsubmit: (ev) => {
ev.preventDefault();
const text = area.value.trim();
if (!text) return;
void (async () => {
problem.textContent = "";
send.disabled = true;
send.textContent = t("own.sending");
try {
await sendReply(listingId, thread, { type: "text", text });
area.value = "";
done();
} catch (e2) {
problem.textContent = e2 instanceof Unauthorized ? t("own.loginBad") : explain(e2);
} finally {
send.disabled = false;
send.textContent = t("own.send");
}
})();
}
},
area,
h("div", { class: "actions" }, send, rel),
problem
);
}
function deleteControl2(listingId, thread) {
const slot = h("p", null);
const ask = () => {
clear(slot);
append(slot, [
t("own.deleteSure"),
" ",
h("button", { type: "button", class: "btn", onclick: () => void deleteThread(listingId, thread).then(() => location.hash = `#/mine/${listingId}`) }, t("own.deleteYes"))
]);
};
slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.delete")));
return slot;
}
function addressCard(listingId, changed) {
const root = h("div", { class: "panel addr" });
let saved = null;
function show() {
clear(root);
append(root, [
h("strong", null, t("own.addrTitle")),
saved ? h("p", { class: "pre" }, [saved.address, saved.phone, saved.email].filter(Boolean).join("\n")) : h("p", { class: "muted" }, t("own.addrNone")),
h("p", { class: "muted small" }, t("own.addrHelp")),
h("button", { type: "button", class: "btn", onclick: edit }, saved ? t("own.addrChange") : t("own.addrAdd"))
]);
}
function edit() {
const a = h("input", { name: "address", value: saved?.address ?? "", maxlength: 300, required: true });
const p = h("input", { name: "phone", value: saved?.phone ?? "", maxlength: 40 });
const e2 = h("input", { name: "email", value: saved?.email ?? "", maxlength: 120 });
const problem = h("p", { class: "error", role: "alert" });
clear(root);
append(root, [
h(
"form",
{
class: "stack",
onsubmit: (ev) => {
ev.preventDefault();
void (async () => {
try {
const next = { address: a.value.trim(), phone: p.value.trim() || void 0, email: e2.value.trim() || void 0 };
if (!next.address) {
problem.textContent = t("own.needAddress");
return;
}
await putAddress(listingId, next);
saved = next;
show();
changed();
} catch (err) {
problem.textContent = explain(err);
}
})();
}
},
h("label", null, t("own.fAddress"), a),
h("label", null, t("own.fPhone"), p),
h("label", null, t("own.fEmail"), e2),
problem,
h(
"div",
{ class: "actions" },
h("button", { type: "submit", class: "btn primary" }, t("own.addrSave")),
h("button", { type: "button", class: "btn", onclick: show }, t("own.addrCancel")),
saved && h(
"button",
{
type: "button",
class: "btn",
onclick: () => void deleteAddress(listingId).then(() => {
saved = null;
show();
changed();
}).catch((err) => {
problem.textContent = explain(err);
})
},
t("own.addrRemove")
)
)
)
]);
a.focus();
}
void getAddress(listingId).then((a) => {
saved = a;
show();
}, () => show());
show();
return { root };
}
function openSheet(listingId, thread, opener, done) {
const host = app2();
const close = () => {
backdrop.remove();
opener.focus();
};
const address = h("input", { name: "address", maxlength: 300, required: true });
const phone = h("input", { name: "phone", maxlength: 40 });
const note = h("textarea", { name: "note", rows: 2, maxlength: 1e3 });
const valid = h("select", { name: "valid" }, ...VALID_DAYS.map((d) => h("option", { value: String(d), selected: d === DEFAULT_DAYS }, d === 1 ? t("own.day") : t("own.days", { n: d }))));
const remember = h("input", { type: "checkbox", name: "remember" });
const rememberRow = h("label", { class: "check" }, remember, " ", t("own.remember"));
const problem = h("p", { class: "error", role: "alert" });
const send = h("button", { type: "submit", class: "btn primary" }, t("own.sendAddress"));
let saved = null;
const form = h(
"form",
{
class: "stack",
onsubmit: (ev) => {
ev.preventDefault();
void (async () => {
problem.textContent = "";
const a = address.value.trim();
if (!a) {
problem.textContent = t("own.needAddress");
return;
}
send.disabled = true;
send.textContent = t("own.sending");
try {
if (remember.checked && (!saved || saved.address !== a)) {
await putAddress(listingId, { address: a, phone: phone.value.trim() || void 0, email: saved?.email });
}
await sendReply(listingId, thread, {
type: "grant",
address: a,
phone: phone.value.trim() || void 0,
note: note.value.trim() || void 0,
valid_days: Number(valid.value)
});
close();
done();
} catch (e2) {
problem.textContent = explain(e2);
send.disabled = false;
send.textContent = t("own.sendAddress");
}
})();
}
},
h("label", null, t("own.fAddress"), address),
h("label", null, t("own.fPhone"), phone),
h("label", null, t("own.fNote"), note),
h("label", null, t("own.fValid"), valid),
rememberRow,
problem,
h("div", { class: "actions" }, send)
);
const closeBtn = h("button", { type: "button", class: "btn close", "aria-label": t("own.close"), onclick: close }, "\xD7");
const backdrop = h(
"div",
{
class: "backdrop",
onclick: (ev) => {
if (ev.target === backdrop) close();
},
onkeydown: (ev) => {
if (ev.key === "Escape") close();
}
},
h("div", { class: "sheet", role: "dialog", "aria-modal": "true", "aria-label": t("own.sheetTitle") }, h("div", { class: "row" }, h("h2", null, t("own.sheetTitle")), closeBtn), h("p", { class: "muted small" }, t("own.sheetHelp")), form)
);
host.append(backdrop);
address.focus();
void getAddress(listingId).then(
(a) => {
saved = a;
if (a) {
if (!address.value) address.value = a.address;
if (!phone.value && a.phone) phone.value = a.phone;
} else {
remember.checked = true;
}
},
() => {
remember.checked = true;
}
);
}
// src/main.ts
var PAGE = 20;
var GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
var app2 = document.getElementById("app");
var app3 = document.getElementById("app");
var statusEl = document.getElementById("status");
function label(prefix, value) {
if (!value) return "";
@@ -4457,8 +5150,8 @@ function searchForm(params) {
),
regions
);
form.addEventListener("submit", (e) => {
e.preventDefault();
form.addEventListener("submit", (e2) => {
e2.preventDefault();
const q = new URLSearchParams();
for (const [k, v] of new FormData(form)) {
if (typeof v === "string" && v.trim() !== "") q.set(k, v.trim());
@@ -4533,9 +5226,9 @@ async function loadResults(gen, q, root) {
}
function showSearch(params) {
const gen = state.generation;
clear(app2);
clear(app3);
const results = h("div", { class: "results", "aria-live": "polite" });
app2.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
app3.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")));
@@ -4620,9 +5313,9 @@ function listingBody(l) {
}
async function showDetail(author, id) {
const gen = state.generation;
clear(app2);
clear(app3);
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
app2.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
app3.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
let raw;
try {
raw = await getListing(author, id);
@@ -4649,6 +5342,14 @@ async function showDetail(author, id) {
}
append(body, [...listingBody(l), verification(raw, l, v)]);
}
function renderNav() {
const nav = document.getElementById("nav");
clear(nav);
append(nav, [
h("a", { href: "#/messages" }, t("nav.messages")),
getToken() && h("a", { href: "#/mine" }, t("nav.owner"))
]);
}
function route() {
state.generation++;
const hash = location.hash.replace(/^#/, "") || "/";
@@ -4657,16 +5358,24 @@ function route() {
const params = new URLSearchParams(q < 0 ? "" : hash.slice(q + 1));
const m = /^\/l\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(path);
const c = /^\/c\/([0-9a-f]{64})\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(path);
if (m) void showDetail(m[1], m[2]);
const login = /^\/login\/([0-9a-f]{16,128})$/.exec(path);
const own = /^\/mine(?:\/([0-9a-f]{32})(?:\/([0-9a-f]{64}))?)?$/.exec(path);
document.body.classList.remove("wide");
if (login) {
setToken(login[1]);
history.replaceState(null, "", location.pathname + location.search + "#/mine");
void showOwner();
} else if (m) void showDetail(m[1], m[2]);
else if (c) void showConversation(c[1], c[2], c[3]);
else if (path === "/messages") showInbox();
else if (own) void showOwner(own[1], own[2]);
else showSearch(params);
renderNav();
window.scrollTo(0, 0);
}
async function boot() {
document.documentElement.lang = lang;
document.getElementById("foot").textContent = t("footer.text");
document.getElementById("nav").append(h("a", { href: "#/messages" }, t("nav.messages")));
try {
state.node = await getStatus();
statusEl.textContent = t("status.line", {