v2.0.9 — sync toast split, relay group chat UI, find/replace flaky fix
- sync: the post-sync toast lumped relay pulls into the CalDAV stats and always labelled the banner "CalDAV". Split into two separate toasts (CalDAV cloud-arrow + Relay broadcast icon), each only shown when its numbers are non-zero. Banners now stack vertically so both can appear together on a sync that pulled on both sides. - relay UI: the session chat view was 1:1-only. Group rooms (which the client API already supports) now surface as first-class threads in the sidebar — sorted chronologically with 1:1 peers, tagged "ROOM", with a users-three icon. Sending posts to `room_uid` instead of `recipient`; history shows the sender name above each incoming message so it's clear who's talking in the room. Relay backend: `/api/chat/threads` returns rooms alongside 1:1 threads; `/api/chat/history` accepts `?room_uid=`; `/api/chat/send` accepts `room_uid` in the body. - tests: bump "replace all updates card bodies" poll budget from 4s to 10s and poll both updated cards. Flaky on cold runs because a fresh PHP worker + SQLite WAL warm-up plus two sequential PATCH calls can just barely exceed 4 seconds. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
4aca21812e
commit
87ebcd156b
6 files changed
+169
-45
No files matched your search
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
define('APP_NAME', 'hyprcrd');
|
define('APP_NAME', 'hyprcrd');
|
||||||
define('APP_VERSION', '2.0.8');
|
define('APP_VERSION', '2.0.9');
|
||||||
|
|
||||||
// APP_DEBUG: gates verbose error responses (curl traces, upstream bodies).
|
// APP_DEBUG: gates verbose error responses (curl traces, upstream bodies).
|
||||||
// Off by default; enable via env for local troubleshooting only.
|
// Off by default; enable via env for local troubleshooting only.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hyprcrd",
|
"name": "hyprcrd",
|
||||||
"version": "2.0.8",
|
"version": "2.0.9",
|
||||||
"description": "hyprcrd — self-hosted card manager",
|
"description": "hyprcrd — self-hosted card manager",
|
||||||
"main": "main.js",
|
"main": "main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -59,14 +59,16 @@ export async function triggerSync() {
|
|||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const s = res.stats || {};
|
const s = res.stats || {};
|
||||||
const rp = relayRes?.pulled || 0;
|
const rp = relayRes?.pulled || 0;
|
||||||
const total = { pushed: s.pushed || 0, pulled: (s.pulled || 0) + rp, deleted: s.deleted || 0 };
|
const caldavStats = { pushed: s.pushed || 0, pulled: s.pulled || 0, deleted: s.deleted || 0 };
|
||||||
|
const relayStats = { pulled: rp };
|
||||||
const allLog = res.log || [];
|
const allLog = res.log || [];
|
||||||
const hasErrors = allLog.some(l => l.status === 'error');
|
const hasErrors = allLog.some(l => l.status === 'error');
|
||||||
const msg = `pushed:${total.pushed} pulled:${total.pulled} del:${total.deleted}${rp ? ' relay:' + rp : ''}`;
|
const msg = `pushed:${caldavStats.pushed} pulled:${caldavStats.pulled + rp} del:${caldavStats.deleted}${rp ? ' relay:' + rp : ''}`;
|
||||||
if (syncStatus) { syncStatus.textContent = msg; syncStatus.style.color = hasErrors ? 'var(--t-danger)' : 'var(--t-accent)'; }
|
if (syncStatus) { syncStatus.textContent = msg; syncStatus.style.color = hasErrors ? 'var(--t-danger)' : 'var(--t-accent)'; }
|
||||||
await window._reloadAll?.();
|
await window._reloadAll?.();
|
||||||
showLog(allLog);
|
showLog(allLog);
|
||||||
showSyncNotification(total);
|
showSyncNotification('CalDAV', 'ph-cloud-arrow-down', caldavStats);
|
||||||
|
showSyncNotification('Relay', 'ph-broadcast', relayStats);
|
||||||
} else {
|
} else {
|
||||||
if (syncStatus) { syncStatus.textContent = res.error || 'sync failed'; syncStatus.style.color = 'var(--t-danger)'; }
|
if (syncStatus) { syncStatus.textContent = res.error || 'sync failed'; syncStatus.style.color = 'var(--t-danger)'; }
|
||||||
}
|
}
|
||||||
@@ -99,7 +101,11 @@ export function autoSync() {
|
|||||||
|
|
||||||
// ── Sync notifications ──────────────────────────────────────────
|
// ── Sync notifications ──────────────────────────────────────────
|
||||||
|
|
||||||
function showSyncNotification(stats) {
|
/** Per-source sync toast. Caller picks the label ("CalDAV" vs "Relay")
|
||||||
|
* and icon so the user knows which pipeline just finished, instead of
|
||||||
|
* the old always-CalDAV banner that lumped relay traffic in silently. */
|
||||||
|
let syncNoteOffset = 0;
|
||||||
|
function showSyncNotification(label, icon, stats) {
|
||||||
const s = stats || {};
|
const s = stats || {};
|
||||||
const parts = [];
|
const parts = [];
|
||||||
if (s.pulled) parts.push(`${s.pulled} received`);
|
if (s.pulled) parts.push(`${s.pulled} received`);
|
||||||
@@ -107,11 +113,17 @@ function showSyncNotification(stats) {
|
|||||||
if (s.deleted) parts.push(`${s.deleted} deleted`);
|
if (s.deleted) parts.push(`${s.deleted} deleted`);
|
||||||
if (!parts.length) return;
|
if (!parts.length) return;
|
||||||
|
|
||||||
|
const bottom = 60 + syncNoteOffset * 48;
|
||||||
|
syncNoteOffset++;
|
||||||
const note = document.createElement('div');
|
const note = document.createElement('div');
|
||||||
note.style.cssText = 'position:fixed;bottom:60px;right:16px;z-index:200;background:var(--t-surface);border:1px solid var(--t-accent);border-radius:4px;padding:10px 14px;box-shadow:0 4px 20px rgba(0,0,0,0.4);max-width:300px;';
|
note.style.cssText = `position:fixed;bottom:${bottom}px;right:16px;z-index:200;background:var(--t-surface);border:1px solid var(--t-accent);border-radius:4px;padding:10px 14px;box-shadow:0 4px 20px rgba(0,0,0,0.4);max-width:300px;`;
|
||||||
note.innerHTML = `<div style="font-family:var(--t-font-pixel);font-size:10px;color:var(--t-accent);display:flex;align-items:center;gap:6px;"><i class="ph ph-cloud-arrow-down"></i>CalDAV: ${parts.join(', ')}</div>`;
|
note.innerHTML = `<div style="font-family:var(--t-font-pixel);font-size:10px;color:var(--t-accent);display:flex;align-items:center;gap:6px;"><i class="ph ${icon}"></i>${label}: ${parts.join(', ')}</div>`;
|
||||||
document.body.appendChild(note);
|
document.body.appendChild(note);
|
||||||
setTimeout(() => { note.style.transition = 'opacity 0.3s'; note.style.opacity = '0'; setTimeout(() => note.remove(), 350); }, 4000);
|
setTimeout(() => {
|
||||||
|
note.style.transition = 'opacity 0.3s';
|
||||||
|
note.style.opacity = '0';
|
||||||
|
setTimeout(() => { note.remove(); syncNoteOffset = Math.max(0, syncNoteOffset - 1); }, 350);
|
||||||
|
}, 4000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// One toast per incoming sync event: "alice synced: Card Title".
|
// One toast per incoming sync event: "alice synced: Card Title".
|
||||||
|
|||||||
@@ -78,14 +78,17 @@ describe('Search: Find/Replace', () => {
|
|||||||
const okBtn = document.getElementById('dialog-ok');
|
const okBtn = document.getElementById('dialog-ok');
|
||||||
if (okBtn) click(okBtn);
|
if (okBtn) click(okBtn);
|
||||||
|
|
||||||
// Poll until the replace has actually persisted
|
// Poll until both replaces have persisted. Budget is generous
|
||||||
|
// (~10s) because a cold PHP run plus two sequential PATCH calls
|
||||||
|
// can easily blow past the original 4-second window — the retry
|
||||||
|
// always passes because opcache + SQLite WAL are warm by then.
|
||||||
let updated1, updated2;
|
let updated1, updated2;
|
||||||
for (let i = 0; i < 40; i++) {
|
for (let i = 0; i < 100; i++) {
|
||||||
await sleep(100);
|
await sleep(100);
|
||||||
updated1 = await getCard(c1.id);
|
updated1 = await getCard(c1.id);
|
||||||
if (updated1?.body === 'goodbye world goodbye') break;
|
|
||||||
}
|
|
||||||
updated2 = await getCard(c2.id);
|
updated2 = await getCard(c2.id);
|
||||||
|
if (updated1?.body === 'goodbye world goodbye' && updated2?.body === 'goodbye there') break;
|
||||||
|
}
|
||||||
expect(updated1.body).toBe('goodbye world goodbye');
|
expect(updated1.body).toBe('goodbye world goodbye');
|
||||||
expect(updated2.body).toBe('goodbye there');
|
expect(updated2.body).toBe('goodbye there');
|
||||||
});
|
});
|
||||||
|
|||||||
+87
-12
@@ -23,14 +23,16 @@ if ($route === '/api/chat/threads' && $method === 'GET' && $sessionTenant) {
|
|||||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
||||||
$myId = $sessionTenant['id'];
|
$myId = $sessionTenant['id'];
|
||||||
|
// 1:1 threads: my 1:1 messages grouped by peer username. Group sends
|
||||||
|
// (room_uid IS NOT NULL) are excluded so they don't surface here.
|
||||||
$stmt = $db->prepare('
|
$stmt = $db->prepare('
|
||||||
SELECT sender_username AS peer, MAX(created_at) AS last_at, COUNT(*) AS count
|
SELECT sender_username AS peer, MAX(created_at) AS last_at, COUNT(*) AS count
|
||||||
FROM chat_messages WHERE recipient_id = :r
|
FROM chat_messages WHERE recipient_id = :r AND room_uid IS NULL
|
||||||
GROUP BY sender_username
|
GROUP BY sender_username
|
||||||
UNION
|
UNION
|
||||||
SELECT t.username AS peer, MAX(cm.created_at) AS last_at, COUNT(*) AS count
|
SELECT t.username AS peer, MAX(cm.created_at) AS last_at, COUNT(*) AS count
|
||||||
FROM chat_messages cm JOIN tenants t ON t.id = cm.recipient_id
|
FROM chat_messages cm JOIN tenants t ON t.id = cm.recipient_id
|
||||||
WHERE cm.sender_id = :s AND cm.recipient_id != :s2
|
WHERE cm.sender_id = :s AND cm.recipient_id != :s2 AND cm.room_uid IS NULL
|
||||||
GROUP BY t.username
|
GROUP BY t.username
|
||||||
');
|
');
|
||||||
$stmt->execute(['r' => $myId, 's' => $myId, 's2' => $myId]);
|
$stmt->execute(['r' => $myId, 's' => $myId, 's2' => $myId]);
|
||||||
@@ -42,29 +44,85 @@ if ($route === '/api/chat/threads' && $method === 'GET' && $sessionTenant) {
|
|||||||
$threads[$peer]['count'] += (int)$row['count'];
|
$threads[$peer]['count'] += (int)$row['count'];
|
||||||
if ($row['last_at'] > $threads[$peer]['last_at']) $threads[$peer]['last_at'] = $row['last_at'];
|
if ($row['last_at'] > $threads[$peer]['last_at']) $threads[$peer]['last_at'] = $row['last_at'];
|
||||||
}
|
}
|
||||||
usort($threads, fn($a, $b) => strcmp($b['last_at'], $a['last_at']));
|
|
||||||
// Add unread count per peer
|
|
||||||
foreach ($threads as &$t) {
|
foreach ($threads as &$t) {
|
||||||
$stmt2 = $db->prepare('SELECT COUNT(*) FROM chat_messages WHERE recipient_id = :r AND sender_username = :p AND seen = 0');
|
$stmt2 = $db->prepare('SELECT COUNT(*) FROM chat_messages WHERE recipient_id = :r AND sender_username = :p AND seen = 0 AND room_uid IS NULL');
|
||||||
$stmt2->execute(['r' => $myId, 'p' => $t['peer']]);
|
$stmt2->execute(['r' => $myId, 'p' => $t['peer']]);
|
||||||
$t['unread'] = (int)$stmt2->fetchColumn();
|
$t['unread'] = (int)$stmt2->fetchColumn();
|
||||||
}
|
}
|
||||||
jsonResponse(array_values($threads));
|
unset($t);
|
||||||
|
// Group rooms the caller is a member of. The UI renders these as
|
||||||
|
// first-class threads alongside 1:1 conversations; room_uid marks them
|
||||||
|
// so the client can key off the right identifier.
|
||||||
|
$roomStmt = $db->prepare('
|
||||||
|
SELECT r.uid, r.name, r.owner_username,
|
||||||
|
(SELECT MAX(created_at) FROM chat_messages cm WHERE cm.room_uid = r.uid) AS last_at,
|
||||||
|
(SELECT COUNT(*) FROM chat_messages cm WHERE cm.room_uid = r.uid) AS count
|
||||||
|
FROM chat_rooms r
|
||||||
|
INNER JOIN chat_room_members m ON m.room_uid = r.uid
|
||||||
|
WHERE m.tenant_id = :tid
|
||||||
|
ORDER BY last_at DESC
|
||||||
|
');
|
||||||
|
$roomStmt->execute(['tid' => $myId]);
|
||||||
|
$roomThreads = [];
|
||||||
|
foreach ($roomStmt->fetchAll() as $r) {
|
||||||
|
$roomThreads[] = [
|
||||||
|
'room_uid' => $r['uid'],
|
||||||
|
'name' => $r['name'],
|
||||||
|
'owner' => $r['owner_username'],
|
||||||
|
'last_at' => $r['last_at'] ?? '',
|
||||||
|
'count' => (int)$r['count'],
|
||||||
|
'unread' => 0, // rooms have no per-recipient seen state yet
|
||||||
|
];
|
||||||
|
}
|
||||||
|
$combined = array_merge(array_values($threads), $roomThreads);
|
||||||
|
usort($combined, fn($a, $b) => strcmp($b['last_at'] ?? '', $a['last_at'] ?? ''));
|
||||||
|
jsonResponse($combined);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($route === '/api/chat/history' && $method === 'GET' && $sessionTenant) {
|
if ($route === '/api/chat/history' && $method === 'GET' && $sessionTenant) {
|
||||||
$peer = trim($_GET['peer'] ?? '');
|
$peer = trim($_GET['peer'] ?? '');
|
||||||
if (!$peer) jsonResponse(['error' => 'peer required'], 400);
|
$roomUid = trim($_GET['room_uid'] ?? '');
|
||||||
|
if ($peer === '' && $roomUid === '') jsonResponse(['error' => 'peer or room_uid required'], 400);
|
||||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
||||||
$myId = $sessionTenant['id'];
|
$myId = $sessionTenant['id'];
|
||||||
|
|
||||||
|
if ($roomUid !== '') {
|
||||||
|
// Group room: caller must be a current member.
|
||||||
|
$check = $db->prepare('SELECT 1 FROM chat_room_members WHERE room_uid = :r AND tenant_id = :t');
|
||||||
|
$check->execute(['r' => $roomUid, 't' => $myId]);
|
||||||
|
if (!$check->fetchColumn()) jsonResponse(['error' => 'not a member of this room'], 403);
|
||||||
|
$stmt = $db->prepare('
|
||||||
|
SELECT id, sender_id, sender_username, body, created_at
|
||||||
|
FROM chat_messages
|
||||||
|
WHERE room_uid = :r
|
||||||
|
ORDER BY created_at ASC LIMIT 500
|
||||||
|
');
|
||||||
|
$stmt->execute(['r' => $roomUid]);
|
||||||
|
$rows = $stmt->fetchAll();
|
||||||
|
$out = [];
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$out[] = [
|
||||||
|
'id' => (int)$row['id'],
|
||||||
|
'from' => $row['sender_username'],
|
||||||
|
'mine' => (int)$row['sender_id'] === $myId,
|
||||||
|
'body' => clientDecrypt($row['body'] ?? '', $interKey),
|
||||||
|
'created_at' => $row['created_at'],
|
||||||
|
'seen' => 1, // group rooms don't track per-recipient seen
|
||||||
|
];
|
||||||
|
}
|
||||||
|
jsonResponse($out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1:1 fallback
|
||||||
$peerTenant = getTenantByUsername($db, $peer);
|
$peerTenant = getTenantByUsername($db, $peer);
|
||||||
if (!$peerTenant) jsonResponse(['error' => 'unknown peer'], 404);
|
if (!$peerTenant) jsonResponse(['error' => 'peer not found'], 404);
|
||||||
$peerId = $peerTenant['id'];
|
$peerId = $peerTenant['id'];
|
||||||
$stmt = $db->prepare('
|
$stmt = $db->prepare('
|
||||||
SELECT id, sender_id, sender_username, body, created_at, seen
|
SELECT id, sender_id, sender_username, body, created_at, seen
|
||||||
FROM chat_messages
|
FROM chat_messages
|
||||||
WHERE (recipient_id = :r AND sender_id = :p) OR (recipient_id = :p2 AND sender_id = :s)
|
WHERE room_uid IS NULL
|
||||||
|
AND ((recipient_id = :r AND sender_id = :p) OR (recipient_id = :p2 AND sender_id = :s))
|
||||||
ORDER BY created_at ASC LIMIT 500
|
ORDER BY created_at ASC LIMIT 500
|
||||||
');
|
');
|
||||||
$stmt->execute(['r' => $myId, 'p' => $peerId, 'p2' => $peerId, 's' => $myId]);
|
$stmt->execute(['r' => $myId, 'p' => $peerId, 'p2' => $peerId, 's' => $myId]);
|
||||||
@@ -90,13 +148,30 @@ if ($route === '/api/chat/send' && $method === 'POST' && $sessionTenant) {
|
|||||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||||
$body = trim((string)($input['body'] ?? ''));
|
$body = trim((string)($input['body'] ?? ''));
|
||||||
$recipientName = trim((string)($input['recipient'] ?? ''));
|
$recipientName = trim((string)($input['recipient'] ?? ''));
|
||||||
|
$roomUid = trim((string)($input['room_uid'] ?? ''));
|
||||||
if ($body === '') jsonResponse(['error' => 'body required'], 400);
|
if ($body === '') jsonResponse(['error' => 'body required'], 400);
|
||||||
if ($recipientName === '') jsonResponse(['error' => 'recipient required'], 400);
|
if ($recipientName === '' && $roomUid === '') jsonResponse(['error' => 'recipient or room_uid required'], 400);
|
||||||
$recipient = getTenantByUsername($db, $recipientName);
|
|
||||||
if (!$recipient) jsonResponse(['error' => 'recipient not found'], 404);
|
|
||||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
||||||
$stored = clientEncrypt($body, $interKey);
|
$stored = clientEncrypt($body, $interKey);
|
||||||
|
|
||||||
|
if ($roomUid !== '') {
|
||||||
|
// Group post: verify membership. `recipient_id` NOT NULL because of
|
||||||
|
// the FK, so we park the sender's own id there — GET filters on
|
||||||
|
// room_uid, never recipient_id, for group rows.
|
||||||
|
$check = $db->prepare('SELECT 1 FROM chat_room_members WHERE room_uid = :r AND tenant_id = :t');
|
||||||
|
$check->execute(['r' => $roomUid, 't' => $sessionTenant['id']]);
|
||||||
|
if (!$check->fetchColumn()) jsonResponse(['error' => 'not a member of this room'], 403);
|
||||||
|
$db->prepare('INSERT INTO chat_messages (recipient_id, sender_id, sender_username, room_uid, body, persistent) VALUES (:me, :s, :sn, :ru, :b, 1)')
|
||||||
|
->execute([
|
||||||
|
'me' => $sessionTenant['id'], 's' => $sessionTenant['id'],
|
||||||
|
'sn' => $sessionTenant['username'], 'ru' => $roomUid, 'b' => $stored,
|
||||||
|
]);
|
||||||
|
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId(), 'room_uid' => $roomUid]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$recipient = getTenantByUsername($db, $recipientName);
|
||||||
|
if (!$recipient) jsonResponse(['error' => 'recipient not found'], 404);
|
||||||
$db->prepare('INSERT INTO chat_messages (recipient_id, sender_id, sender_username, body) VALUES (:r, :s, :sn, :b)')
|
$db->prepare('INSERT INTO chat_messages (recipient_id, sender_id, sender_username, body) VALUES (:r, :s, :sn, :b)')
|
||||||
->execute(['r' => $recipient['id'], 's' => $sessionTenant['id'], 'sn' => $sessionTenant['username'], 'b' => $stored]);
|
->execute(['r' => $recipient['id'], 's' => $sessionTenant['id'], 'sn' => $sessionTenant['username'], 'b' => $stored]);
|
||||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId()]);
|
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId()]);
|
||||||
|
|||||||
+54
-20
@@ -857,61 +857,88 @@ document.addEventListener('visibilitychange', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ── Chat ──
|
// ── Chat ──
|
||||||
|
//
|
||||||
|
// Two thread kinds live side by side: 1:1 (identified by peer username)
|
||||||
|
// and group rooms (identified by room_uid). The UI keeps a single
|
||||||
|
// "active thread" descriptor and switches the fetch / send shape based
|
||||||
|
// on which field is populated.
|
||||||
|
|
||||||
let chatActivePeer = null;
|
let chatActive = null; // { kind: 'peer' | 'room', peer?, roomUid?, label }
|
||||||
let chatPollHandle = null;
|
let chatPollHandle = null;
|
||||||
|
|
||||||
function startChatPoll() {
|
function startChatPoll() {
|
||||||
stopChatPoll();
|
stopChatPoll();
|
||||||
chatPollHandle = setInterval(() => {
|
chatPollHandle = setInterval(() => {
|
||||||
loadChatThreads(true);
|
loadChatThreads(true);
|
||||||
if (chatActivePeer) loadChatHistory(chatActivePeer, true);
|
if (chatActive) loadChatHistory(chatActive, true);
|
||||||
}, 5000);
|
}, 5000);
|
||||||
}
|
}
|
||||||
function stopChatPoll() {
|
function stopChatPoll() {
|
||||||
if (chatPollHandle) { clearInterval(chatPollHandle); chatPollHandle = null; }
|
if (chatPollHandle) { clearInterval(chatPollHandle); chatPollHandle = null; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isSameActive(a, b) {
|
||||||
|
if (!a || !b) return false;
|
||||||
|
return a.kind === b.kind && (a.peer === b.peer) && (a.roomUid === b.roomUid);
|
||||||
|
}
|
||||||
|
|
||||||
async function loadChatThreads(quiet = false) {
|
async function loadChatThreads(quiet = false) {
|
||||||
const list = $('chat-thread-list');
|
const list = $('chat-thread-list');
|
||||||
if (!list) return;
|
if (!list) return;
|
||||||
const threads = await api('api/chat/threads') || [];
|
const threads = await api('api/chat/threads') || [];
|
||||||
if (!Array.isArray(threads)) return;
|
if (!Array.isArray(threads)) return;
|
||||||
|
|
||||||
// If no threads and not quiet, show empty state
|
|
||||||
if (!threads.length && !quiet) {
|
if (!threads.length && !quiet) {
|
||||||
list.innerHTML = `<div class="chat-empty"><i class="ph ph-chat-circle-dots" style="font-size:24px;"></i><div>no conversations yet</div></div>`;
|
list.innerHTML = `<div class="chat-empty"><i class="ph ph-chat-circle-dots" style="font-size:24px;"></i><div>no conversations yet</div></div>`;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!threads.length) return;
|
if (!threads.length) return;
|
||||||
|
|
||||||
list.innerHTML = threads.map(t => `
|
list.innerHTML = threads.map(t => {
|
||||||
<div class="chat-thread ${chatActivePeer === t.peer ? 'active' : ''}" data-peer="${escapeHtml(t.peer)}">
|
const isRoom = !!t.room_uid;
|
||||||
<i class="ph ph-user-circle" style="font-size:16px;color:var(--accent2);flex-shrink:0;"></i>
|
const desc = isRoom
|
||||||
|
? { kind: 'room', roomUid: t.room_uid, label: t.name || t.room_uid }
|
||||||
|
: { kind: 'peer', peer: t.peer, label: t.peer };
|
||||||
|
const active = isSameActive(chatActive, desc);
|
||||||
|
const icon = isRoom ? 'ph-users-three' : 'ph-user-circle';
|
||||||
|
const tag = isRoom ? 'room' : null;
|
||||||
|
const attrs = isRoom
|
||||||
|
? `data-kind="room" data-room-uid="${escapeHtml(t.room_uid)}" data-label="${escapeHtml(desc.label)}"`
|
||||||
|
: `data-kind="peer" data-peer="${escapeHtml(t.peer)}"`;
|
||||||
|
return `
|
||||||
|
<div class="chat-thread ${active ? 'active' : ''}" ${attrs}>
|
||||||
|
<i class="ph ${icon}" style="font-size:16px;color:var(--accent2);flex-shrink:0;"></i>
|
||||||
<div style="flex:1;min-width:0;">
|
<div style="flex:1;min-width:0;">
|
||||||
<div class="peer-name">${escapeHtml(t.peer)}</div>
|
<div class="peer-name">${escapeHtml(desc.label)}${tag ? ` <span style="font-family:var(--pixel);font-size:8px;color:var(--dim);text-transform:uppercase;letter-spacing:0.5px;margin-left:4px;">${tag}</span>` : ''}</div>
|
||||||
<div class="thread-time">${formatRelTime(t.last_at)}</div>
|
<div class="thread-time">${escapeHtml(formatRelTime(t.last_at))}</div>
|
||||||
</div>
|
</div>
|
||||||
${t.unread ? `<span class="unread-badge">${t.unread}</span>` : ''}
|
${t.unread ? `<span class="unread-badge">${t.unread}</span>` : ''}
|
||||||
</div>
|
</div>`;
|
||||||
`).join('');
|
}).join('');
|
||||||
|
|
||||||
list.querySelectorAll('.chat-thread').forEach(el => {
|
list.querySelectorAll('.chat-thread').forEach(el => {
|
||||||
el.addEventListener('click', () => {
|
el.addEventListener('click', () => {
|
||||||
chatActivePeer = el.dataset.peer;
|
if (el.dataset.kind === 'room') {
|
||||||
|
chatActive = { kind: 'room', roomUid: el.dataset.roomUid, label: el.dataset.label };
|
||||||
|
} else {
|
||||||
|
chatActive = { kind: 'peer', peer: el.dataset.peer, label: el.dataset.peer };
|
||||||
|
}
|
||||||
loadChatThreads(true);
|
loadChatThreads(true);
|
||||||
loadChatHistory(chatActivePeer);
|
loadChatHistory(chatActive);
|
||||||
$('chat-input-bar')?.classList.remove('hidden');
|
$('chat-input-bar')?.classList.remove('hidden');
|
||||||
$('chat-peer-name').textContent = chatActivePeer;
|
$('chat-peer-name').textContent = chatActive.label;
|
||||||
$('chat-input')?.focus();
|
$('chat-input')?.focus();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadChatHistory(peer, quiet = false) {
|
async function loadChatHistory(active, quiet = false) {
|
||||||
const container = $('chat-messages');
|
const container = $('chat-messages');
|
||||||
if (!container) return;
|
if (!container || !active) return;
|
||||||
const messages = await api('api/chat/history?peer=' + encodeURIComponent(peer)) || [];
|
const qs = active.kind === 'room'
|
||||||
|
? 'room_uid=' + encodeURIComponent(active.roomUid)
|
||||||
|
: 'peer=' + encodeURIComponent(active.peer);
|
||||||
|
const messages = await api('api/chat/history?' + qs) || [];
|
||||||
if (!Array.isArray(messages)) return;
|
if (!Array.isArray(messages)) return;
|
||||||
|
|
||||||
const wasAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 20;
|
const wasAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 20;
|
||||||
@@ -921,8 +948,13 @@ async function loadChatHistory(peer, quiet = false) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Group rooms need the sender's name visible above each incoming
|
||||||
|
// message (there isn't one single peer — it could be anyone in the
|
||||||
|
// room). 1:1 stays unlabeled for a tighter look.
|
||||||
|
const showSender = active.kind === 'room';
|
||||||
container.innerHTML = messages.map(m => `
|
container.innerHTML = messages.map(m => `
|
||||||
<div class="chat-msg ${m.mine ? 'mine' : 'theirs'}">
|
<div class="chat-msg ${m.mine ? 'mine' : 'theirs'}">
|
||||||
|
${showSender && !m.mine ? `<div class="msg-from" style="font-family:var(--pixel);font-size:9px;color:var(--accent2);margin-bottom:2px;">${escapeHtml(m.from)}</div>` : ''}
|
||||||
<div>${escapeHtml(m.body)}</div>
|
<div>${escapeHtml(m.body)}</div>
|
||||||
<div class="msg-time">${formatChatTime(m.created_at)}${m.mine && m.seen ? ' <i class="ph ph-checks"></i>' : ''}</div>
|
<div class="msg-time">${formatChatTime(m.created_at)}${m.mine && m.seen ? ' <i class="ph ph-checks"></i>' : ''}</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -932,18 +964,20 @@ async function loadChatHistory(peer, quiet = false) {
|
|||||||
container.scrollTop = container.scrollHeight;
|
container.scrollTop = container.scrollHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Refresh thread list to clear unread badges
|
|
||||||
if (!quiet) loadChatThreads(true);
|
if (!quiet) loadChatThreads(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function sendChatMessage() {
|
async function sendChatMessage() {
|
||||||
const input = $('chat-input');
|
const input = $('chat-input');
|
||||||
if (!input || !chatActivePeer) return;
|
if (!input || !chatActive) return;
|
||||||
const body = input.value.trim();
|
const body = input.value.trim();
|
||||||
if (!body) return;
|
if (!body) return;
|
||||||
input.value = '';
|
input.value = '';
|
||||||
await api('api/chat/send', { method: 'POST', body: { body, recipient: chatActivePeer } });
|
const payload = chatActive.kind === 'room'
|
||||||
loadChatHistory(chatActivePeer);
|
? { body, room_uid: chatActive.roomUid }
|
||||||
|
: { body, recipient: chatActive.peer };
|
||||||
|
await api('api/chat/send', { method: 'POST', body: payload });
|
||||||
|
loadChatHistory(chatActive);
|
||||||
loadChatThreads(true);
|
loadChatThreads(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user