cautpartener / client / src / app / views / matches.ts
  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
/**
 * Potriviri (P2/P3): the matching section of the Feed tab — one pool
 * (category × county, the feed's own picker) at a time.
 *
 *  - my-card editor: activate / edit / retire the pool card (blurb ≤300);
 *  - anonymous received-likes counter ("N persoane te-au apreciat" — counts
 *    tokens, never identities) + the honest no-undo / anonymity notes;
 *  - Tinder-style stack: ONE card at a time, drag right = like, left = skip,
 *    plus explicit ❤️ / ✖️ buttons. Skips are local-only; likes cannot be
 *    withdrawn (stated in-app);
 *  - matches list (all pools): mutual likes → open the match conversation.
 *
 * All wire strings render through text nodes (XSS-safe). Tokens and room
 * secrets NEVER reach the DOM or the console.
 */

import { nsKey, RuntimeLimits } from "../../config";
import { clampName, type ContactCard } from "../../core/contacts";
import { sanitizeName } from "../../core/home-log";
import { Session } from "../../core/session";
import type { ChatRoom } from "../../core/chatlog";
import { pollOwnInbox } from "../../public/creq-service";
import {
  browsePool,
  isSkipped,
  likeCard,
  likedMeCount,
  matchByConvId,
  matchConvId,
  matches,
  onMatchesChanged,
  publishCard,
  retireCard,
  sentPendingCount,
  skipCard,
  type PoolCard,
} from "../../public/match-service";
import { CARD_BLURB_MAX } from "../../public/public-doc";
import { categoryKey, isCategorySlug } from "../../public/categories";
import { countyLabel } from "../../public/geo";
import { t } from "../i18n";
import { h, sheet, toast } from "../ui-kit";
import { buildMyCard, fpSpan, myCardName, openTofuSheet } from "./contacts-tab";
import { fmtWhen } from "./chats-tab";

/** Run `cleanup` the moment `el` leaves the document. */
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 });
}

function poolLabel(pool: string): string {
  const bar = pool.indexOf("|");
  const cat = pool.slice(0, bar);
  return `${isCategorySlug(cat) ? t(categoryKey(cat)) : cat} · ${countyLabel(pool.slice(bar + 1))}`;
}

// ---- my-card editor ------------------------------------------------------------

export function openCardEditor(pool: string, onChanged: () => void): void {
  const src = Session.selfroom?.state.mcards.get(pool);
  const input = h("textarea", {
    class: "seed-input",
    rows: 3,
    maxlength: CARD_BLURB_MAX,
    placeholder: t("mtBlurbPh"),
    "data-testid": "mt-blurb",
  }) as HTMLTextAreaElement;
  if (src && !src.retired) input.value = src.blurb;
  const publish = h(
    "button",
    { type: "button", class: "btn", "data-testid": "mt-card-publish" },
    t(src && !src.retired ? "mtEdit" : "mtActivate"),
  ) as HTMLButtonElement;
  const cancel = h("button", { type: "button", class: "btn ghost" }, t("cancel"));
  const body = h(
    "div",
    { "data-testid": "mt-card-editor" },
    h("h2", { class: "sheet-title" }, t("mtMyCardTitle")),
    h("p", { class: "muted small-note" }, poolLabel(pool)),
    h("label", { class: "field-label" }, t("mtBlurbLabel")),
    input,
    h("p", { class: "muted small-note" }, t("mtCardPublicNote", { hours: RuntimeLimits.ttlHours })),
    h("div", { class: "btn-row" }, cancel, publish),
  );
  const s = sheet(body);
  cancel.addEventListener("click", () => s.close());
  publish.addEventListener("click", () => {
    publish.disabled = true;
    void publishCard(pool, input.value)
      .then((r) => {
        if (r.ok) {
          toast(t("mtCardSaved"));
          s.close();
          onChanged();
        } else {
          toast(t(r.reason === "noname" ? "mtNeedName" : "mtCardFailed"));
        }
      })
      .catch(() => toast(t("mtCardFailed")))
      .finally(() => (publish.disabled = false));
  });
}

function myCardSection(pool: string, refresh: () => void): HTMLElement {
  const src = Session.selfroom?.state.mcards.get(pool);
  const active = !!src && !src.retired;
  const statusKey = active ? "mtMyCardActive" : src?.retired ? "mtMyCardRetired" : "mtMyCardNone";
  const buttons: HTMLElement[] = [];
  buttons.push(
    h(
      "button",
      {
        type: "button",
        class: "btn small" + (active ? " ghost" : ""),
        "data-testid": active ? "mt-edit" : "mt-activate",
        onclick: () => openCardEditor(pool, refresh),
      },
      t(active ? "mtEdit" : "mtActivate"),
    ),
  );
  if (active) {
    buttons.push(
      h(
        "button",
        {
          type: "button",
          class: "btn ghost small danger-text",
          "data-testid": "mt-retire",
          onclick: () => {
            void retireCard(pool)
              .then((r) => {
                if (r.ok) {
                  toast(t("mtCardRetiredToast"));
                  refresh();
                } else {
                  toast(t("mtCardFailed"));
                }
              })
              .catch(() => toast(t("mtCardFailed")));
          },
        },
        t("mtRetire"),
      ),
    );
  }
  return h(
    "section",
    { class: "card mt-mycard", "data-testid": "mt-mycard" },
    h("h2", {}, t("mtMyCardTitle")),
    h("p", { class: "muted small-note", "data-testid": "mt-mycard-status", "data-active": active ? "1" : "0" }, t(statusKey)),
    active && src ? h("p", { class: "mt-blurb-preview", "data-testid": "mt-mycard-blurb" }, src.blurb) : null,
    h("div", { class: "btn-row" }, ...buttons),
  );
}

// ---- received-likes counter ----------------------------------------------------

function likesSection(inboxCapped: boolean): HTMLElement {
  const n = likedMeCount();
  const pending = sentPendingCount();
  return h(
    "section",
    { class: "card mt-likes" },
    h(
      "p",
      { class: "mt-liked-line", "data-testid": "mt-liked-count", "data-n": String(n) },
      n === 1 ? t("mtLikedMeOne") : t("mtLikedMeMany", { n }),
    ),
    h("p", { class: "muted small-note" }, t("mtLikedMeNote")),
    // honesty: the shared verify budget cut the inbox walk short — the count
    // (and the pending set) may lag until the slow sweep catches up
    inboxCapped ? h("p", { class: "seed-warn small-note", "data-testid": "mt-inbox-partial" }, t("mtInboxPartial")) : null,
    pending > 0
      ? h(
          "p",
          { class: "muted small-note", "data-testid": "mt-sent-pending" },
          pending === 1 ? t("mtSentPendingOne") : t("mtSentPending", { n: pending }),
        )
      : null,
  );
}

// ---- the swipe stack -----------------------------------------------------------

function stackSection(pool: string, cards: PoolCard[], partial: boolean, refresh: () => void): HTMLElement {
  const box = h("section", { class: "card mt-stack-box" });
  const stack = h("div", { class: "mt-stack", "data-testid": "mt-stack" });
  box.append(stack);
  if (partial) box.append(h("p", { class: "seed-warn small-note", "data-testid": "mt-partial" }, t("mtStackPartial")));
  box.append(h("p", { class: "muted small-note" }, t("mtNoUndoNote")));

  // re-filter the browse snapshot at render time: a like/skip made since the
  // walk must never resurface its card on a redraw
  const state = Session.selfroom?.state;
  const queue = cards.filter((c) => !(state?.mlikes.has(`${c.pub}|${pool}`) ?? false) && !isSkipped(pool, c.pub));

  const drawTop = (): void => {
    stack.replaceChildren();
    const card = queue[0];
    if (!card) {
      stack.append(h("p", { class: "muted empty-note", "data-testid": "mt-empty" }, t("mtStackEmpty")));
      return;
    }
    const el = h(
      "div",
      { class: "mt-card", "data-testid": "mt-card", "data-pub": card.pub },
      h(
        "div",
        { class: "mt-card-head" },
        fpSpan(card.pub, "fp-small"),
        h("a", { class: "mt-card-name", href: `#/u/${card.pub}`, "data-testid": "mt-card-name" }, card.name),
      ),
      h("p", { class: "muted small-note" }, poolLabel(pool)),
    );
    if (card.blurb) {
      const blurb = h("p", { class: "mt-card-blurb", "data-testid": "mt-card-blurb" });
      card.blurb.split("\n").forEach((line, i) => {
        if (i > 0) blurb.append(h("br"));
        blurb.append(document.createTextNode(line));
      });
      el.append(blurb);
    }

    let busy = false;
    const advance = (): void => {
      queue.shift();
      drawTop();
    };
    const doSkip = (): void => {
      if (busy) return;
      skipCard(pool, card.pub);
      el.classList.add("mt-fly-left");
      setTimeout(advance, 150);
    };
    const doLike = (): void => {
      if (busy) return;
      busy = true;
      void likeCard(card)
        .then((r) => {
          if (!r.ok) {
            toast(t("mtLikeFailed"));
            el.style.transform = ""; // spring back a dragged card — the like did NOT go out
            return;
          }
          el.classList.add("mt-fly-right");
          if (r.mutual) {
            toast(t("mtMutualToast"), 5000);
            refresh(); // the new match appears in the list below
          } else {
            toast(t("mtLikeSent"));
          }
          setTimeout(advance, 150);
        })
        .catch(() => {
          toast(t("mtLikeFailed"));
          el.style.transform = "";
        })
        .finally(() => (busy = false));
    };

    // drag gesture: pointer events; beyond ±80 px = decide, else spring back
    let startX: number | null = null;
    let dx = 0;
    let suppressClick = false; // a real drag must not activate the name link
    el.addEventListener("pointerdown", (e) => {
      startX = e.clientX;
      suppressClick = false;
      el.setPointerCapture(e.pointerId);
      el.classList.add("dragging");
    });
    el.addEventListener("pointermove", (e) => {
      if (startX === null) return;
      dx = e.clientX - startX;
      el.style.transform = `translateX(${dx}px) rotate(${dx / 18}deg)`;
    });
    const settle = (): void => {
      el.classList.remove("dragging");
      if (startX === null) return;
      startX = null;
      suppressClick = Math.abs(dx) > 6; // threshold: a tap still navigates
      if (dx > 80) doLike();
      else if (dx < -80) doSkip();
      else el.style.transform = "";
      dx = 0;
    };
    el.addEventListener("pointerup", settle);
    el.addEventListener("pointercancel", settle);
    // the click that follows a drag's pointerup would hit the name link
    el.addEventListener(
      "click",
      (e) => {
        if (!suppressClick) return;
        suppressClick = false;
        e.preventDefault();
        e.stopPropagation();
      },
      true,
    );

    const actions = h(
      "div",
      { class: "mt-actions" },
      h(
        "button",
        { type: "button", class: "btn ghost mt-skip", "aria-label": t("mtSkip"), "data-testid": "mt-skip", onclick: doSkip },
        "✖️",
      ),
      h(
        "button",
        { type: "button", class: "btn mt-like", "aria-label": t("mtLike"), "data-testid": "mt-like", onclick: doLike },
        "❤️",
      ),
    );
    stack.append(el, actions);
  };
  drawTop();
  return box;
}

// ---- the matches list ----------------------------------------------------------

function matchesSection(): HTMLElement {
  const rows = matches().map((m) =>
    h(
      "button",
      {
        type: "button",
        class: "conv-row mt-match-row",
        "data-testid": "mt-match-row",
        "data-pub": m.peer,
        onclick: () => {
          location.hash = `#/c/${matchConvId(m.peer)}`;
        },
      },
      fpSpan(m.peer, "fp-small conv-glyph"),
      h(
        "span",
        { class: "conv-main" },
        h(
          "span",
          { class: "conv-top" },
          h("span", { class: "contact-name" }, m.name || `${m.peer.slice(0, 10)}…`),
          h("span", { class: "conv-time muted" }, fmtWhen(m.ts)),
        ),
        h(
          "span",
          { class: "conv-bottom" },
          h("span", { class: "conv-preview muted" }, poolLabel(m.pool)),
          h("span", { class: "chip chip-strong" }, `❤️ ${t("mtMatchBadge")}`),
        ),
      ),
    ),
  );
  return h(
    "section",
    { class: "card", "data-testid": "mt-matches" },
    h("h2", {}, t("mtMatchesTitle")),
    ...(rows.length > 0 ? rows : [h("p", { class: "muted empty-note", "data-testid": "mt-no-matches" }, t("mtNoMatches"))]),
  );
}

// ---- the section ---------------------------------------------------------------

/**
 * Render the Potriviri section for one pool into `container` (the feed tab's
 * list box). Polls the own inbox once per mount (ingesting any sealed likes)
 * and re-renders on match-state changes.
 */
export function renderMatchSection(container: HTMLElement, pool: string): void {
  let stackBox: HTMLElement | null = null;
  let lastView: { cards: PoolCard[]; capped: boolean } | null = null;
  let inboxCapped = false;

  const draw = (): void => {
    if (!container.isConnected) return;
    const pieces: HTMLElement[] = [myCardSection(pool, draw), likesSection(inboxCapped)];
    if (lastView === null) {
      pieces.push(h("p", { class: "muted empty-note", "data-testid": "mt-loading" }, t("mtLoading")));
    } else {
      stackBox = stackSection(pool, lastView.cards, lastView.capped, draw);
      pieces.push(stackBox);
    }
    pieces.push(matchesSection());
    pieces.push(h("p", { class: "muted small-note mt-honest" }, t("mtHonestNote")));
    container.replaceChildren(...pieces);
  };
  draw();

  const unsub = onMatchesChanged(() => {
    // received/sent likes changed: refresh counter + matches (keep the stack)
    if (container.isConnected) draw();
  });
  onDisconnect(container, unsub);

  // inbox poll (ingests 0x12 likes) + pool browse run in parallel
  void pollOwnInbox()
    .then((v) => {
      inboxCapped = v.capped; // honest hint: the walk may have missed likes
      pruneCardSentFlags(); // matches are freshly derived — safe to prune now
      if (container.isConnected) draw();
    })
    .catch(() => {});
  void browsePool(pool)
    .then((v) => {
      if (!container.isConnected) return;
      lastView = v.reached ? { cards: v.cards, capped: v.capped } : { cards: [], capped: false };
      if (!v.reached) {
        lastView = null;
        container.querySelector('[data-testid="mt-loading"]')?.replaceChildren(document.createTextNode(t("mtNet")));
        return;
      }
      draw();
    })
    .catch(() => {});
}

// ---- match-chat contact exchange (P3) ------------------------------------------

const cardSentKey = (convId: string): string => nsKey(`match-cardsent:${convId}`);

function cardSentFlag(convId: string): boolean {
  try {
    return localStorage.getItem(cardSentKey(convId)) === "1";
  } catch {
    return false;
  }
}

function setCardSentFlag(convId: string): void {
  try {
    localStorage.setItem(cardSentKey(convId), "1");
  } catch {}
}

/**
 * Drop cardsent flags whose match conversation no longer exists (the match
 * dissolved or its tokens aged out) — otherwise the keys accrete forever.
 * Called only after an inbox poll refreshed the received store, so a live
 * match is never mistaken for a dead one on a cold device.
 */
function pruneCardSentFlags(): void {
  try {
    const prefix = nsKey("match-cardsent:");
    const stale: string[] = [];
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (!k || !k.startsWith(prefix)) continue;
      if (!matchByConvId(k.slice(prefix.length))) stale.push(k);
    }
    for (const k of stale) localStorage.removeItem(k);
  } catch {}
}

/** Sender side: offer my contact card into the match room (control op). */
export function openMatchAddContactSheet(convId: string, room: ChatRoom): void {
  const nameInput = h("input", {
    type: "text",
    class: "text-input",
    maxlength: 40,
    autocomplete: "name",
    placeholder: t("ctInviteNamePh"),
    value: myCardName(),
    "data-testid": "mc-add-name",
  }) as HTMLInputElement;
  const send = h("button", { type: "button", class: "btn", "data-testid": "mc-add-send" }, t("mcAddContact")) as HTMLButtonElement;
  const cancel = h("button", { type: "button", class: "btn ghost" }, t("cancel"));
  const body = h(
    "div",
    { "data-testid": "mc-add-sheet" },
    h("h2", { class: "sheet-title" }, t("mcAddContact")),
    h("p", { class: "muted" }, t("mcAddIntro")),
    h("label", { class: "field-label" }, t("ctInviteNameLabel")),
    nameInput,
    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", () => {
    send.disabled = true;
    void (async () => {
      const myName = clampName(nameInput.value);
      await Session.selfroom?.setSettings({ name: myName }).catch(() => {});
      const card = await buildMyCard(myName);
      if (!card || !room.handle) {
        toast(t("mcCardSendFailed"));
        send.disabled = false;
        return;
      }
      const op: { t: string; ts: number; card: ContactCard } = { t: "card", ts: Date.now(), card };
      await room.handle.append(op);
      setCardSentFlag(convId);
      toast(t("mcCardSent"));
      s.close();
    })().catch(() => {
      toast(t("mcCardSendFailed"));
      send.disabled = false;
    });
  });
}

/**
 * Receiver side: the peer's verified card arrived in the match room — run the
 * MANDATORY fingerprint comparison, then addContact (TOFU rules apply). On
 * success, offer to send my own card back unless already sent.
 */
export function openMatchCardReviewSheet(convId: string, card: ContactCard, room: ChatRoom, onDone: () => void): void {
  const svc = Session.contacts;
  if (!svc) return;
  const yes = h("button", { type: "button", class: "btn", "data-testid": "mc-review-yes" }, t("addConfirm")) as HTMLButtonElement;
  const no = h("button", { type: "button", class: "btn ghost", "data-testid": "mc-review-no" }, t("cancel"));
  const body = h(
    "div",
    { "data-testid": "mc-review-sheet" },
    h("h2", { class: "sheet-title" }, t("mcCardOffer", { name: sanitizeName(card.name) })),
    fpSpan(card.pub, "fp-emoji", "mc-review-fp"),
    h("p", { class: "muted" }, t("addCompareBody")),
    h("div", { class: "btn-row" }, no, yes),
  );
  const s = sheet(body);
  no.addEventListener("click", () => s.close());
  yes.addEventListener("click", () => {
    yes.disabled = true;
    void (async () => {
      let stored = false;
      const r = await svc.addContact(card);
      if (r.kind === "added" || r.kind === "unchanged") stored = true;
      else if (r.kind === "key-change") {
        s.close();
        stored = await openTofuSheet(card, r.existing, svc);
      }
      s.close();
      if (!stored) return;
      toast(t("ctAdded"));
      onDone();
      // reciprocity: the peer needs MY card to add me — offer it right away
      if (!cardSentFlag(convId)) openMatchAddContactSheet(convId, room);
    })().catch(() => {
      yes.disabled = false;
    });
  });
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git