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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849 | /**
* Feed tab (M5): Instagram-style public post feed over plain mailbox replay.
*
* Shard picker (category chips × county select, last choice persisted),
* full-bleed post cards (author header with lazy avatar/name, ≤4-image
* swipe carousel with dots, thumb-first + lazy bounded display, expandable
* caption, double-tap + heart likes, comments sheet, share link), composer
* FAB (text + ≤4 images + optional second shard), pull-to-refresh + refresh
* button, infinite scroll via loadOlder, and HONEST footers: the TTL window,
* window-edge / truncation / gap notices, and the per-author render cap.
*
* All wire strings render through text nodes (XSS-safe).
*/
import { RuntimeLimits } from "../../config";
import { activeGroups, clampName } from "../../core/contacts";
import { encodeImage, MediaDecodeError, type EncodedImage } from "../../core/media";
import { Session } from "../../core/session";
import { CATEGORY_SLUGS, categoryKey, isCategorySlug } from "../../public/categories";
import { COUNTY_SLUGS, countyLabel, isCountySlug } from "../../public/geo";
import {
loadShardChoice,
openFeed,
publishPost,
saveShardChoice,
type FeedHandle,
type FeedPost,
type FeedView,
} from "../../public/feed-service";
import { mySource, cachedProfile, resolveProfile } from "../../public/profile-service";
import { POST_IMGS_MAX, POST_TEXT_MAX } from "../../public/public-doc";
import { t } from "../i18n";
import { h, sheet, svgIcon, toast } from "../ui-kit";
import { openActivityComposer, renderActivitiesList } from "./activities";
import { fpSpan } from "./contacts-tab";
import { renderMatchSection } from "./matches";
const POST_BASE = "https://cautpartener.ro/#/p/";
const RENDER_CAP = 100; // rendered cards; loadOlder extends the model, not the DOM past this
/** Run `cleanup` the moment `el` leaves the document (tab switch / route change). */
function onDisconnect(el: HTMLElement, cleanup: () => void): void {
const obs = new MutationObserver(() => {
if (!el.isConnected) {
obs.disconnect();
cleanup();
}
});
obs.observe(document.body, { childList: true, subtree: true });
}
// ---- author header lazy resolution ---------------------------------------------
interface AuthorInfo {
name: string | null;
avatarUrl: string | null;
}
const authorMemo = new Map<string, AuthorInfo>();
const AUTHOR_MEMO_CAP = 300;
const authorInflight = new Set<string>();
let networkResolvesLeft = 0;
/** Insert into the author memo with a small LRU bound (drop the oldest first). */
function memoSet(pub: string, info: AuthorInfo): void {
authorMemo.delete(pub); // re-insert moves it to the newest slot
authorMemo.set(pub, info);
while (authorMemo.size > AUTHOR_MEMO_CAP) {
const oldest = authorMemo.keys().next().value as string | undefined;
if (oldest === undefined) break;
authorMemo.delete(oldest);
}
}
/** Fill name/avatar for a pub from cache instantly, network lazily (budgeted). */
function resolveAuthor(pub: string, apply: (info: AuthorInfo) => void): void {
const memo = authorMemo.get(pub);
if (memo) {
apply(memo);
return;
}
const cached = cachedProfile(pub);
if (cached) {
const info = { name: clampName(cached.profile.name), avatarUrl: cached.avatarUrl };
memoSet(pub, info);
apply(info);
return;
}
if (authorInflight.has(pub) || networkResolvesLeft <= 0) return;
networkResolvesLeft--;
authorInflight.add(pub);
void resolveProfile(pub)
.then((res) => {
const info: AuthorInfo =
res.state === "ok" ? { name: clampName(res.profile.name), avatarUrl: res.avatarUrl } : { name: null, avatarUrl: null };
memoSet(pub, info);
apply(info);
})
.catch(() => {})
.finally(() => authorInflight.delete(pub));
}
// ---- shared card renderer (feed tab + permalink view) ---------------------------
export interface CardHooks {
/** Re-render whatever list holds this card (like counts, hides…). */
refresh: () => void;
}
function timeLabel(ts: number): string {
return new Date(ts).toLocaleString();
}
function heartIcon(cls = "icon"): SVGSVGElement {
return svgIcon("M12 20.5C6.5 16.5 3 13.2 3 9.6 3 7 5 5 7.4 5c1.7 0 3.3.9 4.6 2.6C13.3 5.9 14.9 5 16.6 5 19 5 21 7 21 9.6c0 3.6-3.5 6.9-9 10.9z", cls);
}
/** One full-bleed post card. Exported for the permalink view. */
export function postCard(handle: FeedHandle, post: FeedPost, hooks: CardHooks): HTMLElement {
const card = h("article", { class: "feed-card", "data-testid": "feed-post", "data-cid": post.cidStr, "data-pub": post.pub });
// ---- author header ----
const avatar = h("div", { class: "feed-avatar" }, fpSpan(post.pub, "fp-small"));
const nameEl = h("a", { class: "feed-author", href: `#/u/${post.pub}`, "data-testid": "feed-author" }, `${post.pub.slice(0, 10)}…`);
resolveAuthor(post.pub, (info) => {
if (info.name) nameEl.textContent = info.name;
if (info.avatarUrl) avatar.replaceChildren(h("img", { src: info.avatarUrl, alt: "" }));
});
card.append(
h(
"header",
{ class: "feed-head" },
avatar,
h("div", { class: "feed-head-main" }, nameEl, h("span", { class: "muted feed-time" }, timeLabel(post.ts))),
fpSpan(post.pub, "fp-small feed-head-fp"),
),
);
// ---- audience restriction (M5b) ----
if (post.restricted?.locked) {
// no key on this device: a compact, honest locked card — author + time
// only. The ciphertext itself never reaches the DOM.
card.append(
h("div", { class: "feed-locked", "data-testid": "feed-locked" }, `🔒 ${t("feedLockedPost")}`),
);
return card;
}
if (post.restricted) {
card.append(
h(
"div",
{ class: "chip-row feed-aud-row" },
h(
"span",
{ class: "chip chip-strong", "data-testid": "feed-aud-badge" },
`🔓 ${post.restricted.label ?? t("audVisibleToYou")}`,
),
),
h("p", { class: "muted small-note feed-aud-note", "data-testid": "feed-aud-note" }, t("audPublicMetaNote")),
);
}
// ---- like plumbing (used by carousel double-tap AND the heart button) ----
let liking = false;
const doLike = (burstHost?: HTMLElement): void => {
if (liking || post.likedByMe) return;
if (!Session.identity) {
toast(t("upNoIdentity"));
return;
}
liking = true;
if (burstHost) {
const burst = heartIcon("feed-heart-burst");
burstHost.append(burst);
setTimeout(() => burst.remove(), 900);
}
void handle
.like(post.cidStr)
.then((r) => {
if (r.ok) hooks.refresh();
else toast(t("feedLikeFailed"));
})
.catch(() => toast(t("feedLikeFailed")))
.finally(() => (liking = false));
};
// double-tap detection (touch) + dblclick (pointer); the heart bursts on
// the currently visible carousel slide (or the host itself)
let lastTap = 0;
const burstTarget = (host: HTMLElement): HTMLElement => {
if (!host.classList.contains("feed-carousel")) return host;
const idx = Math.round(host.scrollLeft / Math.max(1, host.clientWidth));
return (host.children[idx] as HTMLElement | undefined) ?? host;
};
const tapLike = (host: HTMLElement): void => {
host.addEventListener("dblclick", () => doLike(burstTarget(host)));
host.addEventListener("touchend", () => {
const now = Date.now();
if (now - lastTap < 320) doLike(burstTarget(host));
lastTap = now;
});
};
// ---- image carousel ----
if (post.imgs.length > 0) {
const track = h("div", { class: "feed-carousel", "data-testid": "feed-carousel" });
const dots = post.imgs.length > 1 ? h("div", { class: "feed-dots" }) : null;
post.imgs.forEach((img, i) => {
const slide = h("div", { class: "feed-slide", style: `aspect-ratio: ${img.w} / ${img.h}` });
const imEl = h("img", { class: "feed-img", alt: "", "data-testid": "feed-img", loading: "lazy" });
slide.append(imEl);
void handle.imageUrl(img, "thumb").then((url) => {
if (url) imEl.src = url;
else slide.append(h("span", { class: "muted feed-img-missing", "data-testid": "feed-img-missing" }, t("feedImgUnavailable")));
});
// debounced single-tap → lightbox; a rapid second tap is the LIKE
// gesture and must not open (or double-open) the viewer
let clickTimer: ReturnType<typeof setTimeout> | null = null;
slide.addEventListener("click", () => {
if (clickTimer !== null) {
clearTimeout(clickTimer);
clickTimer = null;
return;
}
clickTimer = setTimeout(() => {
clickTimer = null;
openLightbox(handle, post, i);
}, 300);
});
track.append(slide);
if (dots) dots.append(h("span", { class: `feed-dot${i === 0 ? " active" : ""}` }));
});
if (dots) {
track.addEventListener(
"scroll",
() => {
const idx = Math.round(track.scrollLeft / Math.max(1, track.clientWidth));
[...dots.children].forEach((d, i) => d.classList.toggle("active", i === idx));
},
{ passive: true },
);
}
tapLike(track);
card.append(track);
if (dots) card.append(dots);
}
// ---- actions ----
const likeBtn = h(
"button",
{
type: "button",
class: `feed-action feed-like${post.likedByMe ? " liked" : ""}`,
"data-testid": "feed-like",
"data-liked": post.likedByMe ? "1" : "0",
title: post.likedByMe ? t("feedLiked") : t("feedLike"),
onclick: () => doLike(likeBtn),
},
heartIcon(),
h("span", { "data-testid": "feed-like-count" }, String(post.likeCount)),
) as HTMLButtonElement;
const commentBtn = h(
"button",
{
type: "button",
class: "feed-action",
"data-testid": "feed-comment",
onclick: () => openCommentsSheet(handle, post.cidStr, hooks),
},
svgIcon("M21 12a8 8 0 0 1-8 8H4l2.4-2.9A8 8 0 1 1 21 12z"),
h("span", { "data-testid": "feed-comment-count" }, String(post.comments.length)),
);
const link = `${POST_BASE}${encodeURIComponent(handle.shard)}/${post.cidStr}`;
const shareBtn = h(
"button",
{
type: "button",
class: "feed-action",
"data-testid": "feed-share",
title: t("feedShare"),
onclick: () => {
void navigator.clipboard?.writeText(link).then(
() => toast(t("linkCopied")),
() => toast(t("copyFailed")),
);
},
},
svgIcon("M12 3v12M12 3l-4 4M12 3l4 4M5 13v6h14v-6"),
);
const actions = h("div", { class: "feed-actions" }, likeBtn, commentBtn, shareBtn);
if (post.own) {
actions.append(
h(
"button",
{
type: "button",
class: "feed-action feed-action-end danger-text",
"data-testid": "feed-delete",
onclick: () => {
handle.hideLocal(post.cidStr);
toast(t("feedDeleteNote", { hours: RuntimeLimits.ttlHours }), 5000);
hooks.refresh();
},
},
t("feedDeleteLocal"),
),
);
} else {
actions.append(
h(
"button",
{
type: "button",
class: "feed-action feed-action-end",
"data-testid": "feed-hide",
onclick: () => {
handle.hideLocal(post.cidStr);
hooks.refresh();
},
},
t("feedHideForeign"),
),
);
}
card.append(actions);
if (post.likedByMe) card.append(h("p", { class: "muted small-note feed-liked-note", "data-testid": "feed-liked-note" }, t("feedLikedNote")));
// ---- caption ----
if (post.text) {
const cap = h("p", { class: "feed-caption clamped", "data-testid": "feed-caption" });
post.text.split("\n").forEach((line, i) => {
if (i > 0) cap.append(h("br"));
cap.append(document.createTextNode(line));
});
if (post.text.length > 140 || post.text.includes("\n")) {
cap.addEventListener("click", () => cap.classList.toggle("clamped"));
}
card.append(cap);
if (post.imgs.length === 0) tapLike(cap);
}
return card;
}
// ---- lightbox (display image, bounded decode) ----------------------------------
function openLightbox(handle: FeedHandle, post: FeedPost, index: number): void {
const img = post.imgs[index];
if (!img) return;
const body = h(
"div",
{ class: "feed-lightbox", "data-testid": "feed-lightbox" },
h("p", { class: "muted", "data-testid": "feed-lightbox-loading" }, t("chatImgLoading")),
);
const s = sheet(body);
body.addEventListener("click", () => s.close());
void handle.imageUrl(img, "display").then((url) => {
if (!body.isConnected) return;
body.replaceChildren(
url
? h("img", { class: "feed-lightbox-img", src: url, alt: "", "data-testid": "feed-display-img" })
: h("p", { class: "muted", "data-testid": "feed-img-missing" }, t("feedImgUnavailable")),
);
});
}
// ---- comments sheet -------------------------------------------------------------
function openCommentsSheet(handle: FeedHandle, postCid: string, hooks: CardHooks): void {
const listBox = h("div", { class: "comment-list feed-comment-list", "data-testid": "feed-comments" });
const drawList = (): void => {
const post = handle.post(postCid);
listBox.replaceChildren();
const comments = post?.comments ?? [];
if (comments.length === 0) {
listBox.append(h("p", { class: "muted empty-note", "data-testid": "feed-no-comments" }, t("upNoComments")));
return;
}
for (const c of comments) {
const row = h(
"div",
{ class: "comment-row", "data-testid": "feed-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" }, timeLabel(c.ts)),
),
);
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);
listBox.append(row);
}
};
drawList();
const body = h("div", { "data-testid": "feed-comments-sheet" }, h("h2", { class: "sheet-title" }, t("upComments")), listBox);
if (Session.identity) {
const input = h("textarea", {
class: "seed-input comment-input",
rows: 2,
maxlength: 1000,
placeholder: t("upCommentPh"),
"data-testid": "feed-comment-input",
}) as HTMLTextAreaElement;
const send = h(
"button",
{ type: "button", class: "btn small", "data-testid": "feed-comment-send" },
t("upCommentSend"),
) as HTMLButtonElement;
send.addEventListener("click", () => {
const post = handle.post(postCid);
if (!post || !input.value.trim()) return;
send.disabled = true;
void handle
.comment(postCid, post.pub, input.value)
.then((r) => {
if (r.ok) {
input.value = "";
drawList();
hooks.refresh();
} else {
toast(t("upCommentFailed"));
}
})
.catch(() => toast(t("upCommentFailed")))
.finally(() => (send.disabled = false));
});
body.append(h("div", { class: "comment-composer" }, input, h("div", { class: "btn-row" }, send)));
} else {
body.append(h("p", { class: "muted small-note" }, t("upNoIdentity")));
}
sheet(body);
}
// ---- composer -------------------------------------------------------------------
function openComposeSheet(shard: string, onPublished: () => void): void {
if (!Session.identity) {
toast(t("upNoIdentity"));
return;
}
const images: EncodedImage[] = [];
const previews = h("div", { class: "feed-previews", "data-testid": "compose-previews" });
const drawPreviews = (): void => {
previews.replaceChildren(
...images.map((im, i) => {
const wrap = h("div", { class: "feed-preview" });
const blob = new Blob([im.thumb as BlobPart], { type: im.mime });
const url = URL.createObjectURL(blob);
const imgEl = h("img", { src: url, alt: "" });
imgEl.addEventListener("load", () => URL.revokeObjectURL(url), { once: true });
wrap.append(
imgEl,
h(
"button",
{
type: "button",
class: "feed-preview-x",
"aria-label": t("pfAvatarRemove"),
onclick: () => {
images.splice(i, 1);
drawPreviews();
},
},
"×",
),
);
return wrap;
}),
);
};
const file = h("input", { type: "file", accept: "image/*", multiple: true, "data-testid": "compose-file" }) as HTMLInputElement;
file.style.display = "none";
const addBtn = h(
"button",
{ type: "button", class: "btn ghost small", "data-testid": "compose-add-img", onclick: () => file.click() },
t("feedComposeAddImg"),
);
file.addEventListener("change", () => {
const files = [...(file.files ?? [])].slice(0, POST_IMGS_MAX - images.length);
file.value = "";
void (async () => {
for (const f of files) {
try {
images.push(await encodeImage(f));
} catch (err) {
toast(t("chatImgFailed"));
if (!(err instanceof MediaDecodeError)) console.warn("post image encode failed", err);
}
}
drawPreviews();
})();
});
const input = h("textarea", {
class: "seed-input",
rows: 4,
maxlength: POST_TEXT_MAX,
placeholder: t("feedComposeTextPh"),
"data-testid": "compose-text",
}) as HTMLTextAreaElement;
// audience selector (M5b): Public, or one of MY contact groups — restricted
// posts are text-only and their likes/comments stay public (stated below)
const groups = Session.selfroom ? activeGroups(Session.selfroom.state) : [];
const audSel = h("select", { class: "text-input", "data-testid": "compose-aud" }) as HTMLSelectElement;
audSel.append(h("option", { value: "" }, t("feedAudPublic")));
for (const g of groups) audSel.append(h("option", { value: g.gid }, g.name));
const audNote = h("p", { class: "muted small-note", "data-testid": "compose-aud-note" }, t("feedAudNote"));
audNote.style.display = "none";
// optional cross-post: a second category in the same county (≤2 shards, §6)
const [cat, county] = [shard.slice(0, shard.indexOf("|")), shard.slice(shard.indexOf("|") + 1)];
const second = h("select", { class: "text-input", "data-testid": "compose-second" }) as HTMLSelectElement;
second.append(h("option", { value: "" }, t("feedComposeNone")));
for (const slug of CATEGORY_SLUGS) {
if (slug !== cat) second.append(h("option", { value: slug }, t(categoryKey(slug))));
}
const publish = h("button", { type: "button", class: "btn", "data-testid": "compose-publish" }, t("feedPublish")) as HTMLButtonElement;
const cancel = h("button", { type: "button", class: "btn ghost" }, t("cancel"));
const imgsLabel = h("label", { class: "field-label" }, t("feedComposeImgs"));
const imgsRow = h("div", { class: "btn-row" }, addBtn);
const body = h(
"div",
{ "data-testid": "compose-sheet" },
h("h2", { class: "sheet-title" }, t("feedCompose")),
h("p", { class: "muted small-note" }, `${t("feedComposeShard")}: ${isCategorySlug(cat) ? t(categoryKey(cat)) : cat} · ${countyLabel(county)}`),
input,
h("label", { class: "field-label" }, t("feedAudLabel")),
audSel,
audNote,
imgsLabel,
previews,
imgsRow,
h("label", { class: "field-label" }, t("feedComposeSecond")),
second,
h("div", { class: "btn-row spaced-top" }, cancel, publish),
file,
);
// restricted posts are TEXT-ONLY (v1): hide the image picker + drop picks
audSel.addEventListener("change", () => {
const restricted = audSel.value !== "";
audNote.style.display = restricted ? "" : "none";
for (const el of [imgsLabel, previews, imgsRow]) el.style.display = restricted ? "none" : "";
if (restricted && images.length > 0) {
images.length = 0;
drawPreviews();
}
});
const s = sheet(body);
cancel.addEventListener("click", () => s.close());
publish.addEventListener("click", () => {
const restricted = audSel.value !== "";
if ((!input.value.trim() && images.length === 0) || (restricted && !input.value.trim())) {
toast(t("feedPublishInvalid"));
return;
}
publish.disabled = true;
const shards = [shard];
if (second.value && isCategorySlug(second.value)) shards.push(`${second.value}|${county}`);
void publishPost(
shards,
input.value,
restricted ? [] : images,
(done, total) => {
publish.textContent = t("feedPublishing", { done, total });
},
restricted ? { gid: audSel.value } : undefined,
)
.then((r) => {
if (r.ok) {
toast(t("feedPublished"));
s.close();
onPublished();
} else if (r.reason === "invalid") {
toast(t("feedPublishInvalid"));
} else {
toast(t("feedPublishFailed"));
}
})
.catch(() => toast(t("feedPublishFailed")))
.finally(() => {
publish.disabled = false;
publish.textContent = t("feedPublish");
});
});
}
// ---- the tab --------------------------------------------------------------------
let currentHandle: FeedHandle | null = null;
/** Which feed section is showing: Postări, Activități or Potriviri (P2). */
let feedSection: "posts" | "acts" | "match" = "posts";
function defaultCounty(): string {
const { src } = mySource();
return isCountySlug(src.county) ? src.county : "romania";
}
export function renderFeedTab(container: HTMLElement): void {
const choice = loadShardChoice();
if (choice && isCategorySlug(choice.cat) && isCountySlug(choice.county)) {
renderFeed(container, choice.cat, choice.county);
return;
}
// First open (no saved pick): land directly in the natural default shard —
// "general" country-wide, or the profile's county when it has one. The
// choice is NOT persisted until the user actively picks something.
renderFeed(container, "general", defaultCounty());
}
function renderFeed(container: HTMLElement, cat: string, county: string): void {
const shard = `${cat}|${county}`;
// picker row: county select + category chips
const countySel = h("select", { class: "text-input feed-county-sel", "data-testid": "feed-county" }) as HTMLSelectElement;
for (const slug of COUNTY_SLUGS) countySel.append(h("option", { value: slug }, countyLabel(slug)));
countySel.value = county;
countySel.addEventListener("change", () => {
saveShardChoice({ cat, county: countySel.value });
renderFeed(container, cat, countySel.value);
});
const chips = h("div", { class: "chip-row feed-chips" });
for (const slug of CATEGORY_SLUGS) {
chips.append(
h(
"button",
{
type: "button",
class: `chip chip-toggle${slug === cat ? " active" : ""}`,
"data-testid": "feed-cat",
"data-cat": slug,
onclick: () => {
saveShardChoice({ cat: slug, county });
renderFeed(container, slug, county);
},
},
t(categoryKey(slug)),
),
);
}
const refreshBtn = h(
"button",
{ type: "button", class: "btn ghost small", "data-testid": "feed-refresh" },
t("feedRefresh"),
) as HTMLButtonElement;
const listBox = h("div", { class: "feed-list", "data-testid": "feed-list" });
const statusBox = h("div", { class: "feed-status" }, h("p", { class: "muted empty-note", "data-testid": "feed-loading" }, t("feedLoading")));
const fab = h(
"button",
{ type: "button", class: "feed-fab", "data-testid": "feed-fab", "aria-label": t("feedCompose") },
svgIcon("M12 5v14M5 12h14"),
);
// segmented control: Postări | Activități | Potriviri (P1/P2 — the same
// category × county picker doubles as the matching pool selector)
const segButtons = new Map<"posts" | "acts" | "match", HTMLButtonElement>();
const segRow = h("div", { class: "seg-row feed-seg" });
for (const [id, key] of [
["posts", "feedSegPosts"],
["acts", "feedSegActs"],
["match", "feedSegMatch"],
] as const) {
const btn = h(
"button",
{
type: "button",
class: `seg-btn${feedSection === id ? " active" : ""}`,
"data-testid": `feed-seg-${id}`,
onclick: () => {
if (feedSection === id) return;
feedSection = id;
for (const [sid, b] of segButtons) b.classList.toggle("active", sid === id);
redraw();
},
},
t(key),
);
segButtons.set(id, btn);
segRow.append(btn);
}
const frame = h(
"div",
{ class: "feed-frame", "data-testid": "feed-frame", "data-shard": shard },
h("div", { class: "feed-picker" }, h("div", { class: "feed-picker-row" }, countySel, refreshBtn), chips, segRow),
statusBox,
listBox,
fab,
);
container.replaceChildren(frame);
// one live handle per mounted feed; close the previous one
currentHandle?.close();
currentHandle = null;
let handle: FeedHandle | null = null;
let renderedCap = RENDER_CAP;
let loadingOlder = false;
let refreshing = false;
const drawView = (view: FeedView): void => {
if (!frame.isConnected || !handle) return;
if (feedSection === "match") return; // the Potriviri section owns the box
const hooks: CardHooks = { refresh: () => handle && drawView(handle.view()) };
listBox.replaceChildren();
statusBox.replaceChildren();
if (view.state === "net") {
statusBox.append(h("p", { class: "muted empty-note", "data-testid": "feed-net" }, t("upNet")));
return;
}
if (view.gap) statusBox.append(h("p", { class: "seed-warn small-note", "data-testid": "feed-gap" }, t("feedGap")));
if (feedSection === "acts") {
// P1: the upcoming-activities index of the SAME shard rooms
renderActivitiesList(listBox, handle, view, { refresh: hooks.refresh, remoteRefresh: doRefresh });
} else if (view.posts.length === 0) {
listBox.append(h("p", { class: "muted empty-note", "data-testid": "feed-empty" }, t("feedEmpty")));
} else {
for (const post of view.posts.slice(0, renderedCap)) listBox.append(postCard(handle, post, hooks));
}
const footer = h("div", { class: "feed-footer" });
if (feedSection === "posts" && view.suppressed > 0) {
footer.append(
h("p", { class: "muted small-note", "data-testid": "feed-capped" }, t("feedCapped", { n: 20 })),
);
}
if (view.truncated) footer.append(h("p", { class: "seed-warn small-note", "data-testid": "feed-truncated" }, t("feedTruncated")));
if (view.atWindowEdge) footer.append(h("p", { class: "muted small-note", "data-testid": "feed-window-edge" }, t("feedWindowEdge")));
footer.append(h("p", { class: "muted small-note", "data-testid": "feed-window-note" }, t("feedWindowNote", { hours: RuntimeLimits.ttlHours })));
listBox.append(footer);
};
const redraw = (): void => {
if (feedSection === "match") {
// P2: the matching section needs no feed handle — it reads the pool
// room directly and owns the list box until the segment changes
statusBox.replaceChildren();
fab.style.display = "none";
renderMatchSection(listBox, shard);
return;
}
fab.style.display = "";
if (handle) drawView(handle.view());
};
if (feedSection === "match") redraw(); // segment persists across re-mounts
const loadOlder = (): void => {
if (!handle || loadingOlder) return;
loadingOlder = true;
renderedCap += RENDER_CAP;
void handle
.loadOlder()
.then(() => handle && drawView(handle.view()))
.catch(() => {})
.finally(() => (loadingOlder = false));
};
const doRefresh = (): void => {
if (feedSection === "match") {
redraw(); // re-browse the pool + re-poll the inbox
return;
}
if (!handle || refreshing) return;
refreshing = true;
refreshBtn.disabled = true;
void handle
.refresh()
.then((v) => drawView(v))
.catch(() => {})
.finally(() => {
refreshing = false;
refreshBtn.disabled = false;
});
};
refreshBtn.addEventListener("click", doRefresh);
fab.addEventListener("click", () => {
if (feedSection === "acts") openActivityComposer(shard, null, doRefresh);
else openComposeSheet(shard, doRefresh);
});
// infinite scroll + pull-to-refresh on the app's scroll container
const scroller = container.closest(".app-main") as HTMLElement | null;
if (scroller) {
const onScroll = (): void => {
if (!frame.isConnected) {
scroller.removeEventListener("scroll", onScroll);
return;
}
if (scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 600) loadOlder();
};
scroller.addEventListener("scroll", onScroll, { passive: true });
let pullStartY: number | null = null;
const onTouchStart = (e: TouchEvent): void => {
pullStartY = scroller.scrollTop <= 0 ? e.touches[0].clientY : null;
};
const onTouchEnd = (e: TouchEvent): void => {
if (!frame.isConnected) {
scroller.removeEventListener("touchstart", onTouchStart);
scroller.removeEventListener("touchend", onTouchEnd);
return;
}
if (pullStartY !== null && e.changedTouches[0].clientY - pullStartY > 80 && scroller.scrollTop <= 0) doRefresh();
pullStartY = null;
};
scroller.addEventListener("touchstart", onTouchStart, { passive: true });
scroller.addEventListener("touchend", onTouchEnd, { passive: true });
}
networkResolvesLeft = 4; // author network-resolve budget per feed mount
void openFeed(shard)
.then((hd) => {
if (!frame.isConnected) {
hd.close();
return;
}
handle = hd;
currentHandle = hd;
hd.onLiveUpdate = () => drawView(hd.view());
drawView(hd.view());
// leaving the feed (tab switch in lobby.select, or a route change) drops
// this frame from the DOM: close the handle so the gossipsub feedTopic is
// left and the background live-refresh timer stops (no leaked handle).
onDisconnect(frame, () => {
hd.close();
if (currentHandle === hd) currentHandle = null;
});
})
.catch(() => {
statusBox.replaceChildren(h("p", { class: "muted empty-note", "data-testid": "feed-net" }, t("upNet")));
});
}
|