1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564 | /**
* #/u/<pub> — the public profile view (M4). Renders PURELY from public-plane
* mailbox replay (§1/§6): a stranger's fresh browser resolves the profile with
* the owner offline. Honest states everywhere: resolving spinner → profile OR
* unavailable-with-reason (TTL expiry note per §7, spam-budget state, network
* failure with retry) and a stale-cache banner when the local cache answered.
*
* All strings render through text nodes (XSS-safe); the bio renders as plain
* text with line breaks only.
*/
import { RuntimeLimits } from "../../config";
import { decodeRestrictedProfile } from "../../core/audience";
import { clampName } from "../../core/contacts";
import { Session } from "../../core/session";
import type { SealedSectionRef } from "../../public/public-doc";
import { fingerprintOf } from "../../lib/identity";
import { listComments, postComment, type ModView, type PublicComment } from "../../public/comment-service";
import { creqSentTo, sendCreq } from "../../public/creq-service";
import { categoryKey, isCategorySlug } from "../../public/categories";
import { countyLabel } from "../../public/geo";
import { publishMod, resolveProfile, type ResolvedProfile } from "../../public/profile-service";
import { t } from "../i18n";
import { h, sheet, toast } from "../ui-kit";
import { fpSpan, myCardName } from "./contacts-tab";
import { presetTab } from "./lobby";
const PROFILE_BASE = "https://cautpartener.ro/#/u/";
const PUB_RE = /^[A-Za-z0-9_-]{43}$/;
function frame(...children: (HTMLElement | null)[]): HTMLElement {
return h(
"div",
{ class: "profile-view", "data-testid": "up-view" },
h(
"div",
{ class: "profile-view-inner" },
h("a", { class: "btn ghost small", href: "#/" }, t("backHome")),
...children.filter((c): c is HTMLElement => c !== null),
),
);
}
function terminal(root: HTMLElement, glyph: string, msg: string, testid: string, extra?: HTMLElement): void {
root.replaceChildren(
frame(
h(
"section",
{ class: "card placeholder" },
h("div", { class: "glyph" }, glyph),
h("p", { class: "add-msg", "data-testid": testid }, msg),
extra ?? null,
),
),
);
}
export function renderUserProfile(root: HTMLElement, pub: string): void {
if (!PUB_RE.test(pub)) {
terminal(root, "🚫", t("upInvalid"), "up-invalid");
return;
}
void runFlow(root, pub);
}
async function runFlow(root: HTMLElement, pub: string): Promise<void> {
root.replaceChildren(
frame(
h(
"section",
{ class: "card placeholder" },
h("div", { class: "glyph" }, "🔍"),
h("p", { class: "muted", "data-testid": "up-loading" }, t("upLoading")),
),
),
);
const res = await resolveProfile(pub);
if (!root.isConnected) return;
if (res.state === "none") {
const retry = h(
"button",
{ type: "button", class: "btn", "data-testid": "up-retry", onclick: () => void runFlow(root, pub) },
t("upRetry"),
);
if (res.reason === "budget") terminal(root, "⚠️", t("upSpam"), "up-spam", retry);
else if (res.reason === "net") terminal(root, "📡", t("upNet"), "up-net", retry);
else terminal(root, "⏳", t("upUnavailable", { hours: RuntimeLimits.ttlHours }), "up-unavailable", retry);
return;
}
await renderProfile(root, pub, res);
}
async function renderProfile(root: HTMLElement, pub: string, res: ResolvedProfile): Promise<void> {
const fp = await fingerprintOf(pub);
if (!root.isConnected) return;
const myPub = Session.identity?.identity.publicKeyB64 ?? null;
const isOwn = myPub === pub;
const p = res.profile;
// ---- header card -----------------------------------------------------------
const avatar = res.avatarUrl
? h("img", { class: "up-avatar", src: res.avatarUrl, alt: "", "data-testid": "up-avatar" })
: h("div", { class: "up-avatar up-avatar-fallback", "data-testid": "up-avatar-fallback", title: fp.hex }, fp.emoji);
const chips = h(
"div",
{ class: "chip-row up-chips" },
h("span", { class: "chip chip-strong", "data-testid": "up-county" }, countyLabel(p.county)),
// open slug vocabulary: a category this build doesn't know (published by
// a newer client) renders as its raw slug in a neutral chip — never drop
...p.categories.map((c) =>
h("span", { class: "chip", "data-testid": "up-cat", "data-cat": c }, isCategorySlug(c) ? t(categoryKey(c)) : c),
),
);
const bio = h("p", { class: "up-bio", "data-testid": "up-bio" });
p.bio.split("\n").forEach((line, i) => {
if (i > 0) bio.append(h("br"));
bio.append(document.createTextNode(line));
});
const link = `${PROFILE_BASE}${pub}`;
const copyBtn = h(
"button",
{
type: "button",
class: "btn ghost small",
"data-testid": "up-copy-link",
onclick: () => {
void navigator.clipboard?.writeText(link).then(
() => toast(t("linkCopied")),
() => toast(t("copyFailed")),
);
},
},
t("copyLink"),
);
const actions = h("div", { class: "btn-row" }, copyBtn);
const contact = myPub ? Session.contacts?.state.contacts.get(pub) : undefined;
if (isOwn) {
actions.append(
h(
"a",
{ class: "btn small", href: "#/", "data-testid": "up-edit", onclick: () => presetTab("profile") },
t("upEdit"),
),
);
} else if (contact?.status === "active") {
actions.append(
h("a", { class: "btn small", href: `#/c/${pub}`, "data-testid": "up-message" }, t("upMessage")),
);
} else if (myPub) {
if (creqSentTo(pub)) {
actions.append(h("span", { class: "chip", "data-testid": "up-creq-sent" }, t("upCreqSent")));
} else {
const creqBtn = h(
"button",
{ type: "button", class: "btn small", "data-testid": "up-creq" },
t("upCreq"),
) as HTMLButtonElement;
creqBtn.addEventListener("click", () => openCreqSheet(pub, clampName(p.name), creqBtn));
actions.append(creqBtn);
}
}
const header = h(
"section",
{ class: "card up-head" },
res.source === "cache" ? h("p", { class: "seed-warn", "data-testid": "up-stale" }, t("upStale")) : null,
isOwn ? h("p", { class: "muted small-note", "data-testid": "up-own" }, t("upOwn")) : null,
h(
"div",
{ class: "up-head-row" },
avatar,
h(
"div",
{ class: "up-head-main" },
h("h2", { "data-testid": "up-name" }, clampName(p.name)),
h("div", { class: "fp-emoji up-fp", "data-testid": "up-fp", title: fp.hex }, fp.emoji),
),
),
p.bio ? bio : null,
chips,
actions,
);
// ---- sealed sections (M5b) -------------------------------------------------
const sealedBox = p.sealed && p.sealed.length > 0 ? sealedSectionsCard(pub, p.sealed) : null;
// ---- upcoming activities strip (P1) ----------------------------------------
const actsBox = h("section", { class: "card", "data-testid": "up-acts" }, h("h2", {}, t("upActs")));
// ---- posts grid (M5) -------------------------------------------------------
const gridBox = h("section", { class: "card", "data-testid": "up-grid" }, h("h2", {}, t("upPosts")));
// ---- comments section ------------------------------------------------------
const commentsBox = h("section", { class: "card", "data-testid": "up-comments" }, h("h2", {}, t("upComments")));
root.replaceChildren(frame(header, sealedBox, actsBox, gridBox, commentsBox));
void renderActivitiesStrip(actsBox, pub, res).catch(() => {});
void renderPostsGrid(gridBox, pub, res).catch(() => {});
await renderComments(commentsBox, pub, res, isOwn, myPub !== null, () => void runFlow(root, pub));
}
/** Plain-text paragraph with preserved line breaks (XSS-safe text nodes). */
function multiline(text: string, cls: string, testid?: string): HTMLElement {
const el = h("p", { class: cls, ...(testid ? { "data-testid": testid } : {}) });
text.split("\n").forEach((line, i) => {
if (i > 0) el.append(h("br"));
el.append(document.createTextNode(line));
});
return el;
}
/**
* Audience-sealed profile sections (M5b): each entry starts as an honest lock
* chip; boxes this device holds a key for (owner gkeys / member rgrants)
* unseal asynchronously into the section content with an open-lock badge.
* The ciphertext itself never reaches the DOM.
*/
function sealedSectionsCard(pub: string, sealed: SealedSectionRef[]): HTMLElement {
const box = h("section", { class: "card", "data-testid": "up-sealed" }, h("h2", {}, t("upSealedTitle")));
for (const ref of sealed) {
const row = h(
"div",
{ class: "up-sealed-row", "data-gidhint": ref.gidHint },
h("span", { class: "chip", "data-testid": "up-sealed-locked" }, `🔒 ${t("upSealedLocked")}`),
);
box.append(row);
void (async () => {
const audience = Session.audience;
if (!audience) return; // signed out / stack booting — stays locked
const pt = await audience.unseal(pub, ref).catch(() => null);
const sec = pt ? decodeRestrictedProfile(pt) : null;
if (!sec || !row.isConnected) return;
const label = audience.labelFor(pub, ref.gidHint) ?? t("audVisibleToYou");
const parts: HTMLElement[] = [
h(
"div",
{ class: "chip-row" },
h("span", { class: "chip chip-strong", "data-testid": "up-sealed-open" }, `🔓 ${label}`),
),
];
if (sec.about) parts.push(multiline(sec.about, "up-bio", "up-sealed-about"));
if (sec.contact) parts.push(h("p", { class: "up-sealed-contact", "data-testid": "up-sealed-contact" }, sec.contact));
for (const f of sec.custom) {
parts.push(
h(
"p",
{ class: "up-sealed-field", "data-testid": "up-sealed-field" },
h("span", { class: "muted" }, `${f.label}: `),
f.val,
),
);
}
row.replaceChildren(...parts);
})();
}
box.append(h("p", { class: "muted small-note", "data-testid": "up-sealed-note" }, t("upSealedNote")));
return box;
}
/**
* "Activități viitoare" (P1): the author's UPCOMING activities, resolved from
* the feed rooms of their DECLARED shards (the author-grid mechanism,
* kind-filtered). Same honest limit as the grid: only what those rooms hold
* within the TTL window is discoverable.
*/
async function renderActivitiesStrip(box: HTMLElement, pub: string, res: ResolvedProfile): Promise<void> {
// wire-validated slug shapes; unknown (newer-client) slugs still derive rooms
const cats = res.profile.categories;
if (cats.length === 0) {
box.append(h("p", { class: "muted empty-note", "data-testid": "up-no-acts" }, t("upNoActs")));
return;
}
const loading = h("p", { class: "muted" }, t("feedLoading"));
box.append(loading);
const [{ loadAuthorActivities }, { fmtRange, activityHash }] = await Promise.all([
import("../../public/feed-service"),
import("./activities"),
]);
const { acts, reachedAll } = await loadAuthorActivities(pub, cats, res.profile.county);
if (!box.isConnected) return;
loading.remove();
if (!reachedAll) {
box.append(h("p", { class: "seed-warn small-note" }, t("upGridPartial")));
}
if (acts.length === 0) {
box.append(h("p", { class: "muted empty-note", "data-testid": "up-no-acts" }, t("upNoActs")));
return;
}
const list = h("div", { class: "up-acts-list", "data-testid": "up-acts-list" });
for (const a of acts) {
list.append(
h(
"a",
{ class: "up-act-row", href: activityHash(a.shard, a.org, a.aid), "data-testid": "up-act-row", "data-aid": a.aid },
h("span", { class: "up-act-title" }, a.restricted ? `🔒 ${a.title}` : a.title),
h("span", { class: "muted up-act-when" }, fmtRange(a.start, a.end)),
),
);
}
box.append(list);
}
/**
* The author's photo grid, resolved from the feed rooms of their DECLARED
* shards (profile categories × county). Honest limitation shown in-app: only
* posts discoverable there, within the TTL window, can appear — nothing links
* a pub to posts in shards the profile doesn't declare.
*/
async function renderPostsGrid(box: HTMLElement, pub: string, res: ResolvedProfile): Promise<void> {
// wire-validated slug shapes; unknown (newer-client) slugs still derive rooms
const cats = res.profile.categories;
if (cats.length === 0) {
box.append(h("p", { class: "muted empty-note", "data-testid": "up-no-posts" }, t("upNoPosts")));
return;
}
const loading = h("p", { class: "muted", "data-testid": "up-grid-loading" }, t("feedLoading"));
box.append(loading);
const { loadAuthorGrid } = await import("../../public/feed-service");
const grid = await loadAuthorGrid(pub, cats, res.profile.county);
if (!box.isConnected) return;
loading.remove();
if (!grid.reachedAll) {
box.append(h("p", { class: "seed-warn small-note", "data-testid": "up-grid-partial" }, t("upGridPartial")));
}
if (grid.posts.length === 0) {
box.append(h("p", { class: "muted empty-note", "data-testid": "up-no-posts" }, t("upNoPosts")));
} else {
const gridEl = h("div", { class: "up-post-grid", "data-testid": "up-post-grid" });
for (const p of grid.posts) {
const tile = h("a", {
class: "up-post-tile",
href: `#/p/${encodeURIComponent(p.shard)}/${p.cidStr}`,
"data-testid": "up-post-tile",
"data-cid": p.cidStr,
});
if (p.restricted) {
// audience-restricted post: honest lock tile (the permalink unseals
// for key-holders; strangers keep seeing the lock there too)
tile.append(h("span", { class: "up-tile-text up-tile-lock", "data-testid": "up-tile-lock" }, "🔒"));
} else if (p.img) {
void grid.thumbUrl(p).then((url) => {
if (url) tile.append(h("img", { src: url, alt: "" }));
else tile.append(h("span", { class: "up-tile-text" }, p.text.slice(0, 60) || "…"));
});
} else {
tile.append(h("span", { class: "up-tile-text" }, p.text.slice(0, 60)));
}
gridEl.append(tile);
}
box.append(gridEl);
}
box.append(h("p", { class: "muted small-note", "data-testid": "up-grid-note" }, t("upGridNote", { hours: RuntimeLimits.ttlHours })));
}
// ---- creq sheet ----------------------------------------------------------------
function openCreqSheet(targetPub: string, targetName: string, trigger: HTMLButtonElement): void {
const nameInput = h("input", {
type: "text",
class: "text-input",
maxlength: 40,
autocomplete: "name",
placeholder: t("ctInviteNamePh"),
value: myCardName(),
"data-testid": "creq-name",
}) as HTMLInputElement;
const msgInput = h("textarea", {
class: "seed-input",
rows: 3,
maxlength: 200,
placeholder: t("upCreqMsgPh"),
"data-testid": "creq-msg",
}) as HTMLTextAreaElement;
const send = h("button", { type: "button", class: "btn", "data-testid": "creq-send" }, t("upCreqSend")) as HTMLButtonElement;
const cancel = h("button", { type: "button", class: "btn ghost" }, t("cancel"));
const body = h(
"div",
{ "data-testid": "creq-sheet" },
h("h2", { class: "sheet-title" }, `${t("upCreqTitle")} — ${targetName}`),
h("p", { class: "muted" }, t("upCreqExplain")),
h("label", { class: "field-label" }, t("ctInviteNameLabel")),
nameInput,
h("label", { class: "field-label" }, t("upCreqMsg")),
msgInput,
h("div", { class: "btn-row" }, cancel, send),
);
const s = sheet(body);
cancel.addEventListener("click", () => s.close());
const gate = (): void => {
send.disabled = clampName(nameInput.value).length === 0;
};
nameInput.addEventListener("input", gate);
gate();
send.addEventListener("click", () => {
const name = clampName(nameInput.value);
if (!name) return;
send.disabled = true;
void (async () => {
await Session.selfroom?.setSettings({ name }).catch(() => {});
const r = await sendCreq(targetPub, name, msgInput.value);
if (r.ok || (!r.ok && r.reason === "duplicate")) {
toast(t("upCreqOk"));
trigger.replaceWith(h("span", { class: "chip", "data-testid": "up-creq-sent" }, t("upCreqSent")));
s.close();
} else {
toast(t("upCreqFailed"));
send.disabled = false;
}
})().catch(() => {
toast(t("upCreqFailed"));
send.disabled = false;
});
});
}
// ---- comments -------------------------------------------------------------------
async function renderComments(
box: HTMLElement,
pub: string,
res: ResolvedProfile,
isOwn: boolean,
signedIn: boolean,
refreshAll: () => void,
): Promise<void> {
const mod: ModView = { hidden: res.hidden, blocked: res.blocked };
// the OWNER moderates from the freshest local mod source (a just-published
// mod op may still be ahead of the replayed doc)
if (isOwn) {
const m = Session.selfroom?.state.modSrc;
if (m) {
for (const c of m.hidden) mod.hidden.add(c);
for (const b of m.blocked) mod.blocked.add(b);
}
}
if (res.profile.commentPolicy === "off") {
box.append(h("p", { class: "muted", "data-testid": "up-comments-off" }, t("upCommentsOff")));
return;
}
const listBox = h("div", { class: "comment-list" });
box.append(listBox);
const drawList = (comments: PublicComment[], truncated: boolean): void => {
listBox.replaceChildren();
if (truncated)
listBox.append(h("p", { class: "muted small-note", "data-testid": "up-comments-truncated" }, t("upCommentsTruncated")));
if (comments.length === 0) {
listBox.append(h("p", { class: "muted empty-note", "data-testid": "up-no-comments" }, t("upNoComments")));
return;
}
for (const c of comments) {
const row = h(
"div",
{ class: "comment-row", "data-testid": "comment-item", "data-cid": c.cidStr, "data-pub": c.pub },
h(
"div",
{ class: "comment-head" },
fpSpan(c.pub, "fp-small"),
h("a", { class: "mono comment-author", href: `#/u/${c.pub}` }, `${c.pub.slice(0, 10)}…`),
h("span", { class: "muted comment-time" }, new Date(c.ts).toLocaleString()),
),
);
const textEl = h("p", { class: "comment-text" });
c.text.split("\n").forEach((line, i) => {
if (i > 0) textEl.append(h("br"));
textEl.append(document.createTextNode(line));
});
row.append(textEl);
if (isOwn) {
row.append(
h(
"div",
{ class: "btn-row" },
h(
"button",
{
type: "button",
class: "btn ghost small",
"data-testid": "comment-hide",
onclick: () => void moderate({ hide: [c.cidStr] }, refreshAll),
},
t("upHide"),
),
h(
"button",
{
type: "button",
class: "btn ghost small danger-ghost",
"data-testid": "comment-block",
onclick: () => void moderate({ block: [c.pub] }, refreshAll),
},
t("upBlock"),
),
),
);
}
listBox.append(row);
}
};
// composer for signed-in users
if (signedIn) {
const input = h("textarea", {
class: "seed-input comment-input",
rows: 2,
maxlength: 1000,
placeholder: t("upCommentPh"),
"data-testid": "comment-input",
}) as HTMLTextAreaElement;
const send = h(
"button",
{ type: "button", class: "btn small", "data-testid": "comment-send" },
t("upCommentSend"),
) as HTMLButtonElement;
send.addEventListener("click", () => {
const text = input.value;
if (!text.trim()) return;
send.disabled = true;
void postComment(pub, text)
.then(async (r) => {
if (r.ok) {
toast(t("upCommentPosted"));
input.value = "";
const fresh = await listComments(pub, mod);
if (fresh.state === "ok" && listBox.isConnected) drawList(fresh.comments, fresh.truncated);
} else {
toast(t("upCommentFailed"));
}
send.disabled = false;
})
.catch(() => {
toast(t("upCommentFailed"));
send.disabled = false;
});
});
box.append(h("div", { class: "comment-composer" }, input, h("div", { class: "btn-row" }, send)));
} else {
box.append(h("p", { class: "muted small-note", "data-testid": "up-no-id-note" }, t("upNoIdentity")));
}
if (isOwn) box.append(h("p", { class: "muted small-note" }, t("upModNote")));
const list = await listComments(pub, mod);
if (!listBox.isConnected) return;
if (list.state === "net") {
listBox.replaceChildren(h("p", { class: "muted", "data-testid": "up-comments-net" }, t("upNet")));
return;
}
drawList(list.comments, list.truncated);
}
async function moderate(patch: { hide?: string[]; block?: string[] }, refreshAll: () => void): Promise<void> {
const ok = await publishMod(patch).catch(() => false);
toast(ok ? t("upModDone") : t("upModFailed"));
if (ok) refreshAll();
}
|