@alexsun-top/opencode-chat-room 0.3.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +44 -11
  3. package/README.zh-CN.md +40 -10
  4. package/package.json +4 -1
  5. package/plugin.ts +26 -10
  6. package/server/announcement-routes.ts +34 -0
  7. package/server/assets/MERMAID-LICENSE +21 -0
  8. package/server/assets/NOTICE.txt +2 -1
  9. package/server/assets/base.css +43 -27
  10. package/server/assets/chat/announcements.js +119 -0
  11. package/server/assets/chat/events.js +180 -6
  12. package/server/assets/chat/index.js +6 -0
  13. package/server/assets/chat/markdown.js +214 -11
  14. package/server/assets/chat/members.js +4 -1
  15. package/server/assets/chat/messages.js +57 -77
  16. package/server/assets/chat/questions.js +204 -0
  17. package/server/assets/chat/receipts.js +117 -0
  18. package/server/assets/chat/rooms.js +11 -6
  19. package/server/assets/chat/state.js +64 -18
  20. package/server/assets/conversation.css +58 -17
  21. package/server/assets/mermaid-11.12.2.min.js +2811 -0
  22. package/server/assets/responsive.css +47 -23
  23. package/server/chat-server.ts +41 -12
  24. package/server/chat.html +51 -10
  25. package/server/member-routes.ts +3 -0
  26. package/server/newrooms.ts +2 -0
  27. package/server/resource-routes.ts +65 -0
  28. package/server/wake.ts +2 -2
  29. package/skills/chatroom/SKILL.md +92 -0
  30. package/src/agent-receipts.ts +4 -4
  31. package/src/announcement-tool.ts +25 -0
  32. package/src/announcements.ts +16 -0
  33. package/src/center-client.ts +32 -2
  34. package/src/center-inbox.ts +9 -9
  35. package/src/chatroom-skill.ts +15 -0
  36. package/src/plugin-notifications.ts +7 -9
  37. package/src/resource-upload.ts +50 -0
  38. package/src/resources.ts +104 -0
  39. package/src/room-service.ts +5 -0
  40. package/src/sqlite-state.ts +83 -13
  41. package/src/store.ts +4 -11
  42. package/src/v1-plugin.ts +6 -1
  43. package/src/v2-plugin.ts +39 -8
@@ -8,8 +8,19 @@ export function initMessages(app) {
8
8
  let pollDelay = 2000;
9
9
 
10
10
  app.autoGrow = (textarea) => {
11
+ textarea.style.overflowY = "hidden";
12
+ const style = getComputedStyle(textarea), line = parseFloat(style.lineHeight);
13
+ const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
14
+ const border = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
15
+ if (!textarea.value) {
16
+ textarea.style.height = `${Math.max(line + padding + border, parseFloat(style.minHeight) || 0)}px`;
17
+ return;
18
+ }
11
19
  textarea.style.height = "auto";
12
- textarea.style.height = `${Math.min(textarea.scrollHeight, 132)}px`;
20
+ const limit = line * 5 + padding;
21
+ const overflow = textarea.scrollHeight > limit + 1;
22
+ textarea.style.height = `${Math.min(textarea.scrollHeight, limit) + border}px`;
23
+ textarea.style.overflowY = overflow ? "auto" : "hidden";
13
24
  };
14
25
  app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
15
26
  app.updateDraftCount = () => app.setText($("#draftCount"), "messageCount", { count: $("#msgInput").value.length });
@@ -48,7 +59,7 @@ export function initMessages(app) {
48
59
  app.renderFailedMessages();
49
60
  try {
50
61
  const updated = await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, {
51
- method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text }),
62
+ method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion) }),
52
63
  });
53
64
  const entry = app.state.rooms.get(roomId);
54
65
  if (entry) {
@@ -73,6 +84,7 @@ export function initMessages(app) {
73
84
  }
74
85
  };
75
86
  app.jumpToBottom = () => {
87
+ app.state.readAnchorGuard = null;
76
88
  $("#thread").scrollTop = $("#thread").scrollHeight;
77
89
  const entry = app.state.room && app.state.rooms.get(app.state.room.id);
78
90
  app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
@@ -97,6 +109,10 @@ export function initMessages(app) {
97
109
  const thread = $("#thread");
98
110
  if (!room || !entry || document.hidden || !document.hasFocus()
99
111
  || thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
112
+ if (app.state.readAnchorGuard?.roomId === room.id) {
113
+ if (performance.now() > app.state.userScrollIntentUntil) return;
114
+ app.state.readAnchorGuard = null;
115
+ }
100
116
  const timestamp = room.messages.reduce((latest, message) => Math.max(latest, message.createdAt), entry.readTs);
101
117
  if (!timestamp || timestamp <= entry.readTs) return;
102
118
  try {
@@ -105,6 +121,7 @@ export function initMessages(app) {
105
121
  });
106
122
  if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation) return;
107
123
  entry.readTs = timestamp;
124
+ app.saveReadTs(room.id, timestamp);
108
125
  entry.unreadOverflow = false;
109
126
  for (const [id, message] of entry.unreadIds) if (message.createdAt <= timestamp) entry.unreadIds.delete(id);
110
127
  app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
@@ -126,10 +143,7 @@ export function initMessages(app) {
126
143
  row.append(text);
127
144
  } else {
128
145
  const direct = app.state.room.kind === "direct";
129
- const sameName = app.state.memberSessions.get(app.state.room.id)?.filter((member) => member.name === message.senderId);
130
- const own = direct ? message.senderId === LS.sessionID
131
- : message.senderSessionID ? message.senderSessionID === LS.sessionID
132
- : message.senderId === app.state.myName && sameName?.length === 1 && sameName[0].sessionID === LS.sessionID;
146
+ const own = isOwnMessage(message, app);
133
147
  const sender = direct
134
148
  ? app.state.room.participants.find((person) => person.id === message.senderId)?.name || app.t("guest")
135
149
  : message.senderId;
@@ -146,7 +160,7 @@ export function initMessages(app) {
146
160
  renderMarkdown(body, message.text, app);
147
161
  const content = document.createElement("div");
148
162
  content.className = "msg-content";
149
- content.append(body, receiptDetails(message, app));
163
+ content.append(body, app.createReceiptButton(message, own));
150
164
  row.append(meta, content);
151
165
  }
152
166
  const copy = document.createElement("button");
@@ -161,23 +175,6 @@ export function initMessages(app) {
161
175
  return row;
162
176
  };
163
177
 
164
- app.renderReceiptData = (roomId, receipts) => {
165
- const thread = $("#thread"), edge = thread.getBoundingClientRect();
166
- const atBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
167
- const anchor = Array.from($("#msgList").querySelectorAll("[data-msg-id]")).find((node) => node.getBoundingClientRect().bottom > edge.top);
168
- const anchorId = anchor?.dataset.msgId, anchorTop = anchor ? anchor.getBoundingClientRect().top - edge.top : 0;
169
- for (const receipt of receipts) app.state.receipts.set(`${roomId}\0${receipt.messageID}`, receipt.readers);
170
- for (const row of document.querySelectorAll(`#msgList [data-msg-id]`)) {
171
- const message = app.state.room?.messages.find((item) => item.id === row.dataset.msgId);
172
- if (message?.roomId === roomId || app.state.room?.id === roomId && message) updateReceiptDetails(row, message, app);
173
- }
174
- if (atBottom) thread.scrollTop = thread.scrollHeight;
175
- else if (anchorId) {
176
- const next = $("#msgList").querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
177
- if (next) thread.scrollTop += next.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorTop;
178
- }
179
- };
180
-
181
178
  app.renderMessages = (live = false) => {
182
179
  const thread = $("#thread"), list = $("#msgList"), messages = app.state.room.messages;
183
180
  const nearBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
@@ -269,7 +266,7 @@ export function initMessages(app) {
269
266
  };
270
267
 
271
268
  app.send = async () => {
272
- const input = $("#msgInput"), text = input.value.trim(), room = app.state.room;
269
+ const input = $("#msgInput"), text = input.value.trim(), room = app.state.room, isQuestion = Boolean(app.isQuestionSending?.());
273
270
  if (!text || !room) return;
274
271
  const revision = app.state.draftRevision.get(room.id) || 0;
275
272
  app.closeMention();
@@ -281,7 +278,7 @@ export function initMessages(app) {
281
278
  app.hideSendError();
282
279
  try {
283
280
  const updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
284
- method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text }),
281
+ method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, isQuestion }),
285
282
  });
286
283
  if (app.state.room?.id !== room.id) return;
287
284
  app.state.room = updated;
@@ -302,7 +299,7 @@ export function initMessages(app) {
302
299
  } catch (error) {
303
300
  const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
304
301
  const failures = app.state.failedMessages.get(room.id) || [];
305
- app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text }]);
302
+ app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, isQuestion }]);
306
303
  app.renderFailedMessages();
307
304
  if (app.state.room?.id !== room.id) return;
308
305
  if (unchanged) app.clearDraft(room.id);
@@ -355,18 +352,22 @@ export function initMessages(app) {
355
352
  return;
356
353
  }
357
354
  if (data.member !== true || !Array.isArray(data.items)) return;
358
- const items = data.items, previousReceivedTs = entry?.receivedTs || 0, messages = app.state.room.messages;
359
- const known = new Set(messages.map((message) => message.id));
360
- let sawSystem = false, added = 0;
361
- for (const item of items) {
362
- if (item.senderId === "system") sawSystem = true;
363
- if (known.has(item.id)) continue;
364
- messages.push({ ...item, roomId });
365
- known.add(item.id);
366
- entry?.unreadIds.set(item.id, item);
367
- if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
368
- added++;
369
- }
355
+ const items = data.items, previousReceivedTs = entry?.receivedTs || 0, messages = app.state.room.messages;
356
+ const known = new Set(messages.map((message) => message.id));
357
+ const previousUnreadOverflow = Boolean(entry?.unreadOverflow);
358
+ let sawSystem = false, added = 0, unreadChanged = false;
359
+ for (const item of items) {
360
+ if (item.senderId === "system") sawSystem = true;
361
+ const wasKnown = known.has(item.id);
362
+ if (!wasKnown) {
363
+ messages.push({ ...item, roomId }); known.add(item.id);
364
+ if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
365
+ added++;
366
+ }
367
+ if (entry && item.createdAt > entry.readTs && !(wasKnown && isOwnMessage(item, app)) && !entry.unreadIds.has(item.id)) {
368
+ entry.unreadIds.set(item.id, item); unreadChanged = true;
369
+ }
370
+ }
370
371
  if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
371
372
  if (entry) entry.unreadOverflow = Boolean(data.hasMore);
372
373
  if (messages.length > 500) messages.splice(0, messages.length - 500);
@@ -375,7 +376,7 @@ export function initMessages(app) {
375
376
  await app.refreshRoomMeta(roomId, generation);
376
377
  if (!isCurrentPoll(roomId, generation)) return;
377
378
  }
378
- if (added) {
379
+ if (added || unreadChanged || entry && previousUnreadOverflow !== entry.unreadOverflow) {
379
380
  app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : app.state.unread + added;
380
381
  app.updateBadge();
381
382
  }
@@ -449,6 +450,16 @@ export function initMessages(app) {
449
450
 
450
451
  function trimMessages(list, app) {
451
452
  if (list.children.length <= 400 || hasMessageSelection(list)) return;
453
+ const saved = app.state.positions.get(app.state.room?.id), rows = [...list.querySelectorAll("[data-msg-id]")];
454
+ const anchor = saved?.messageId && rows.find((row) => row.dataset.msgId === saved.messageId);
455
+ if (anchor && rows.indexOf(anchor) < rows.length - 280) {
456
+ const recent = rows.at(-300);
457
+ while (list.firstElementChild && list.firstElementChild !== anchor) list.firstElementChild.remove();
458
+ let next = anchor.nextElementSibling;
459
+ while (next && next !== recent) { const after = next.nextElementSibling; next.remove(); next = after; }
460
+ const gap = document.createElement("li"); gap.className = "gap"; app.setText(gap, "messagesBetweenOmitted"); anchor.after(gap);
461
+ return;
462
+ }
452
463
  while (list.children.length > 300) list.removeChild(list.firstChild);
453
464
  if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
454
465
  const gap = document.createElement("li");
@@ -458,43 +469,12 @@ function trimMessages(list, app) {
458
469
  }
459
470
  }
460
471
 
461
- function receiptDetails(message, app) {
462
- const details = document.createElement("details");
463
- details.className = "message-readers";
464
- const summary = document.createElement("summary"), count = document.createElement("span"), list = document.createElement("ul");
465
- count.className = "receipt-count";
466
- list.className = "receipt-reader-list";
467
- summary.append(count);
468
- details.append(summary, list);
469
- updateReceiptDetails(details.closest("li") || details, message, app);
470
- return details;
471
- }
472
-
473
- function updateReceiptDetails(row, message, app) {
474
- const details = row.matches?.("details.message-readers") ? row : row.querySelector("details.message-readers");
475
- if (!details) return;
476
- const detailsKey = `${app.state.room?.id || message.roomId || ""}\0${message.id}`;
477
- const senderID = message.senderSessionID || (app.state.room?.kind === "direct" ? message.senderId : "");
478
- const readers = (app.state.receipts.get(detailsKey) || []).filter((reader) => reader.sessionID !== senderID);
479
- details.hidden = readers.length === 0;
480
- const summary = details.querySelector("summary"), label = app.t("receiptCount", { count: readers.length });
481
- summary.setAttribute("aria-label", label);
482
- summary.title = label;
483
- details.querySelector(".receipt-count").textContent = String(readers.length);
484
- const list = details.querySelector(".receipt-reader-list");
485
- list.textContent = "";
486
- const members = app.state.memberSessions.get(app.state.room?.id) || [];
487
- for (const reader of readers) {
488
- const row = document.createElement("li"), name = document.createElement("span"), evidence = document.createElement("span");
489
- const duplicates = members.filter((member) => member.name === reader.name).length > 1 || readers.filter((item) => item.name === reader.name).length > 1;
490
- name.textContent = `${reader.name}${duplicates ? ` · ${reader.sessionID.slice(0, 8)}` : ""}${reader.currentMember === false ? ` · ${app.t("departedMember")}` : ""}`;
491
- evidence.textContent = app.t(`receiptEvidence_${reader.evidence}`);
492
- evidence.title = evidence.textContent;
493
- evidence.setAttribute("aria-label", evidence.textContent);
494
- row.dataset.readerSessionId = reader.sessionID;
495
- row.append(name, evidence);
496
- list.append(row);
497
- }
472
+ function isOwnMessage(message, app) {
473
+ const room = app.state.room, direct = room.kind === "direct";
474
+ const sameName = app.state.memberSessions.get(room.id)?.filter((member) => member.name === message.senderId);
475
+ return direct ? message.senderId === LS.sessionID
476
+ : message.senderSessionID ? message.senderSessionID === LS.sessionID
477
+ : message.senderId === app.state.myName && sameName?.length === 1 && sameName[0].sessionID === LS.sessionID;
498
478
  }
499
479
 
500
480
  }
@@ -0,0 +1,204 @@
1
+ import { LS } from "./state.js";
2
+
3
+ export function initQuestions(app) {
4
+ const $ = app.$, pending = new Map(), selected = new Map(), drafts = new Map(), questionMode = new Map(), submitting = new Set();
5
+ let request = 0;
6
+ const panel = $("#questionPanel"), trigger = $("#btnQuestions"), list = $("#questionList"), status = $("#questionStatus");
7
+ app.isQuestionSending = () => Boolean(questionMode.get(app.state.room?.id));
8
+ $("#questionToggle").addEventListener("change", (event) => {
9
+ if (app.state.room) questionMode.set(app.state.room.id, event.target.checked);
10
+ });
11
+
12
+ const renderMessage = app.renderMessage;
13
+ app.renderMessage = (message, live) => {
14
+ const row = renderMessage(message, live);
15
+ if (message.isQuestion) {
16
+ row.classList.add("question-message");
17
+ const mark = document.createElement("span");
18
+ mark.className = "question-mark";
19
+ mark.textContent = app.t("questionLabel");
20
+ mark.setAttribute("aria-label", app.t("questionLabel"));
21
+ row.querySelector(".msg-meta")?.append(mark);
22
+ }
23
+ return row;
24
+ };
25
+
26
+ function render(roomId) {
27
+ const items = pending.get(roomId) || [];
28
+ const active = app.state.room?.id === roomId;
29
+ if (active) {
30
+ $("#questionBadge").textContent = items.length > 99 ? "99+" : String(items.length);
31
+ $("#questionBadge").hidden = !items.length;
32
+ trigger.setAttribute("aria-label", `${app.t("questions")}: ${items.length}`);
33
+ list.textContent = "";
34
+ for (const question of items) {
35
+ const item = document.createElement("li"), button = document.createElement("button");
36
+ button.type = "button";
37
+ button.className = "question-item";
38
+ button.dataset.questionId = question.id;
39
+ button.setAttribute("aria-pressed", String(selected.get(roomId) === question.id));
40
+ button.textContent = question.text;
41
+ item.append(button);
42
+ list.append(item);
43
+ }
44
+ status.hidden = items.length > 0 || status.dataset.error === "true";
45
+ if (!items.length && status.dataset.error !== "true") app.setText(status, "questionsEmpty");
46
+ renderReply(roomId);
47
+ }
48
+ }
49
+
50
+ function renderReply(roomId) {
51
+ const box = $("#questionReply"), question = (pending.get(roomId) || []).find((item) => item.id === selected.get(roomId));
52
+ if (question && box.dataset.roomId === roomId && box.dataset.questionId === question.id) {
53
+ const key = `${roomId}\0${question.id}`, input = box.querySelector("textarea"), send = box.querySelector("button");
54
+ box.hidden = false;
55
+ if (input && send) send.disabled = !input.value.trim() || submitting.has(key);
56
+ return;
57
+ }
58
+ box.textContent = "";
59
+ box.dataset.roomId = question ? roomId : "";
60
+ box.dataset.questionId = question?.id || "";
61
+ box.hidden = !question;
62
+ if (!question) return;
63
+ const heading = document.createElement("p"), form = document.createElement("form"), input = document.createElement("textarea"), send = document.createElement("button");
64
+ heading.className = "question-reply-quote";
65
+ heading.textContent = question.text;
66
+ form.className = "question-reply-form";
67
+ input.className = "input";
68
+ input.rows = 2;
69
+ input.maxLength = 2000;
70
+ input.placeholder = app.t("answerPlaceholder");
71
+ input.setAttribute("aria-label", app.t("answerPlaceholder"));
72
+ input.value = drafts.get(`${roomId}\0${question.id}`) || "";
73
+ const key = `${roomId}\0${question.id}`;
74
+ send.type = "submit";
75
+ send.className = "btn primary small";
76
+ send.textContent = app.t("sendAnswer");
77
+ send.disabled = !input.value.trim() || submitting.has(key);
78
+ input.addEventListener("input", () => {
79
+ drafts.set(`${roomId}\0${question.id}`, input.value);
80
+ send.disabled = !input.value.trim() || submitting.has(key);
81
+ });
82
+ form.addEventListener("submit", (event) => {
83
+ event.preventDefault();
84
+ void answer(roomId, question.id, input.value.trim(), send);
85
+ });
86
+ form.append(input, send);
87
+ box.append(heading, form);
88
+ }
89
+
90
+ async function load(roomId = app.state.room?.id) {
91
+ if (!roomId) return;
92
+ const id = ++request;
93
+ if (app.state.room?.id === roomId && !pending.has(roomId)) {
94
+ app.setText(status, "questionsLoading");
95
+ status.hidden = false;
96
+ }
97
+ try {
98
+ const result = await app.api(`/rooms/${encodeURIComponent(roomId)}/questions`);
99
+ if (id !== request || app.state.room?.id !== roomId || !Array.isArray(result.questions)) return;
100
+ pending.set(roomId, result.questions);
101
+ status.dataset.error = "false";
102
+ status.hidden = true;
103
+ render(roomId);
104
+ } catch (error) {
105
+ if (id !== request || app.state.room?.id !== roomId) return;
106
+ if (error.status === 401) app.openChatSettings();
107
+ status.dataset.error = "true";
108
+ app.setText(status, "questionsFailed");
109
+ status.hidden = false;
110
+ render(roomId);
111
+ }
112
+ }
113
+
114
+ async function answer(roomId, questionId, text, button) {
115
+ const key = `${roomId}\0${questionId}`;
116
+ if (!text || submitting.has(key)) return;
117
+ submitting.add(key);
118
+ button.disabled = true;
119
+ renderReply(roomId);
120
+ try {
121
+ const result = await app.api(`/rooms/${encodeURIComponent(roomId)}/questions/${encodeURIComponent(questionId)}/answers`, {
122
+ method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text }),
123
+ });
124
+ const entry = app.state.rooms.get(roomId);
125
+ if (entry && result.answer && !entry.room.messages.some((item) => item.id === result.answer.id)) {
126
+ entry.room.messages.push({ ...result.answer, roomId });
127
+ entry.room.messages.sort((left, right) => left.createdAt - right.createdAt);
128
+ if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
129
+ if (app.state.room?.id === roomId) app.renderMessages(true);
130
+ }
131
+ pending.set(roomId, (pending.get(roomId) || []).filter((item) => item.id !== result.questionID));
132
+ if (selected.get(roomId) === questionId) selected.delete(roomId);
133
+ drafts.delete(`${roomId}\0${questionId}`);
134
+ if (app.state.room?.id === roomId) render(roomId);
135
+ void load(roomId);
136
+ } catch (error) {
137
+ if (error.status === 409 || error.status === 404) {
138
+ await load(roomId);
139
+ if (error.status === 409 && app.state.room?.id === roomId && !(pending.get(roomId) || []).some((item) => item.id === questionId)) {
140
+ if (selected.get(roomId) === questionId) selected.delete(roomId);
141
+ drafts.delete(`${roomId}\0${questionId}`);
142
+ app.setText(status, "questionAlreadyAnswered");
143
+ status.dataset.error = "true";
144
+ status.hidden = false;
145
+ render(roomId);
146
+ }
147
+ } else if (error.status === 401 && app.state.room?.id === roomId) {
148
+ app.openChatSettings();
149
+ app.showSendError("sendAuth");
150
+ } else if (app.state.room?.id === roomId) {
151
+ app.setText(status, "answerFailed");
152
+ status.hidden = false;
153
+ }
154
+ } finally {
155
+ submitting.delete(key);
156
+ if (app.state.room?.id === roomId) renderReply(roomId);
157
+ }
158
+ }
159
+
160
+ trigger.addEventListener("click", () => {
161
+ const open = panel.hidden;
162
+ app.closePanels();
163
+ panel.hidden = !open;
164
+ trigger.setAttribute("aria-expanded", String(open));
165
+ if (open) {
166
+ void load();
167
+ $("#questionHeading").focus();
168
+ }
169
+ });
170
+ $("#btnRefreshQuestions").addEventListener("click", () => void load());
171
+ list.addEventListener("click", (event) => {
172
+ event.stopPropagation();
173
+ const button = event.target.closest("[data-question-id]");
174
+ if (!button || !app.state.room) return;
175
+ selected.set(app.state.room.id, button.dataset.questionId);
176
+ render(app.state.room.id);
177
+ $("#questionReply textarea")?.focus();
178
+ });
179
+
180
+ const closePanels = app.closePanels;
181
+ app.closePanels = () => {
182
+ closePanels();
183
+ panel.hidden = true;
184
+ trigger.setAttribute("aria-expanded", "false");
185
+ };
186
+ document.addEventListener("keydown", (event) => {
187
+ if (event.key === "Escape" && !panel.hidden) {
188
+ app.closePanels();
189
+ trigger.focus();
190
+ }
191
+ });
192
+ const activateRoom = app.activateRoom;
193
+ app.activateRoom = (roomId) => {
194
+ activateRoom(roomId);
195
+ $("#questionToggle").checked = Boolean(questionMode.get(roomId));
196
+ void load(roomId);
197
+ };
198
+ const applyLocale = app.applyLocale;
199
+ app.applyLocale = () => {
200
+ applyLocale();
201
+ if (app.state.room) render(app.state.room.id);
202
+ };
203
+ setInterval(() => { if (app.state.room) void load(); }, 5000);
204
+ }
@@ -0,0 +1,117 @@
1
+ export function initReceipts(app) {
2
+ const $ = app.$, panel = $("#readerPanel");
3
+ let selectedID = "", trigger = null;
4
+ app.createReceiptButton = (message, own) => {
5
+ const button = document.createElement("button");
6
+ button.type = "button";
7
+ button.className = "message-readers";
8
+ button.dataset.messageId = message.id;
9
+ button.dataset.ownMessage = String(own);
10
+ button.setAttribute("aria-haspopup", "true");
11
+ button.setAttribute("aria-controls", "readerPanel");
12
+ updateButton(button, message, own);
13
+ return button;
14
+ };
15
+ app.renderReceiptData = (roomId, receipts) => {
16
+ const thread = $("#thread"), edge = thread.getBoundingClientRect();
17
+ const atBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
18
+ const anchor = [...$("#msgList").querySelectorAll("[data-msg-id]")].find((node) => node.getBoundingClientRect().bottom > edge.top);
19
+ const anchorId = anchor?.dataset.msgId, anchorTop = anchor ? anchor.getBoundingClientRect().top - edge.top : 0;
20
+ for (const receipt of receipts) app.state.receipts.set(`${roomId}\0${receipt.messageID}`, receipt.readers);
21
+ for (const button of $("#msgList").querySelectorAll(".message-readers")) {
22
+ const message = app.state.room?.messages.find((item) => item.id === button.dataset.messageId);
23
+ if (message) updateButton(button, message);
24
+ }
25
+ if (atBottom) thread.scrollTop = thread.scrollHeight;
26
+ else if (anchorId) {
27
+ const next = $("#msgList").querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
28
+ if (next) thread.scrollTop += next.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorTop;
29
+ }
30
+ if (selectedID) { renderPanel(); positionPanel(); }
31
+ };
32
+ $("#msgList").addEventListener("click", (event) => {
33
+ const button = event.target.closest(".message-readers");
34
+ if (!button) return;
35
+ if (selectedID === button.dataset.messageId) close(true);
36
+ else open(button.dataset.messageId, button);
37
+ });
38
+ $("#btnCloseReaders").addEventListener("click", () => close(true));
39
+ document.addEventListener("click", (event) => {
40
+ if (selectedID && !event.target.closest("#readerPanel, .message-readers")) close(false);
41
+ });
42
+ document.addEventListener("keydown", (event) => {
43
+ if (event.key === "Escape" && selectedID) { event.preventDefault(); close(true); }
44
+ });
45
+ window.addEventListener("resize", positionPanel);
46
+ window.addEventListener("scroll", positionPanel, true);
47
+
48
+ function open(id, button) {
49
+ selectedID = id; trigger = button;
50
+ button.setAttribute("aria-expanded", "true");
51
+ panel.hidden = false; renderPanel(); positionPanel();
52
+ requestAnimationFrame(() => $("#readerHeading").focus({ preventScroll: true }));
53
+ }
54
+ function close(restoreFocus) {
55
+ if (!selectedID) return;
56
+ const previous = trigger;
57
+ selectedID = ""; trigger = null;
58
+ previous?.setAttribute("aria-expanded", "false");
59
+ panel.hidden = true;
60
+ if (restoreFocus && previous?.isConnected) previous.focus({ preventScroll: true });
61
+ }
62
+ function positionPanel() {
63
+ if (!selectedID || panel.hidden) return;
64
+ if (!trigger?.isConnected) return close(false);
65
+ const anchor = trigger.getBoundingClientRect(), margin = 12;
66
+ if (anchor.bottom <= 0 || anchor.top >= innerHeight) return close(false);
67
+ const width = Math.min(320, innerWidth - margin * 2);
68
+ panel.style.width = `${width}px`;
69
+ const belowSpace = innerHeight - margin - anchor.bottom - 8;
70
+ const aboveSpace = anchor.top - margin - 8;
71
+ const placeBelow = belowSpace >= aboveSpace;
72
+ panel.style.maxHeight = `${Math.max(0, placeBelow ? belowSpace : aboveSpace)}px`;
73
+ const height = panel.getBoundingClientRect().height;
74
+ const left = Math.max(margin, Math.min(anchor.right - width, innerWidth - width - margin));
75
+ const top = placeBelow ? anchor.bottom + 8 : anchor.top - height - 8;
76
+ panel.style.left = `${left}px`; panel.style.top = `${top}px`;
77
+ }
78
+ function renderPanel() {
79
+ const message = app.state.room?.messages.find((item) => item.id === selectedID);
80
+ if (!message) return close(false);
81
+ const readers = readersFor(message);
82
+ $("#readerHeading").textContent = app.t("readerPanelTitle");
83
+ $("#readerCount").textContent = readerStatus(message, readers);
84
+ $("#readerExcerpt").textContent = message.text;
85
+ const list = $("#readerList"); list.textContent = "";
86
+ const members = app.state.memberSessions.get(app.state.room.id) || [];
87
+ for (const reader of readers) {
88
+ const row = document.createElement("li"), name = document.createElement("span"), evidence = document.createElement("span");
89
+ const duplicates = members.filter((member) => member.name === reader.name).length > 1 || readers.filter((item) => item.name === reader.name).length > 1;
90
+ name.textContent = `${reader.name}${duplicates ? ` · ${reader.sessionID.slice(0, 8)}` : ""}${reader.currentMember === false ? ` · ${app.t("departedMember")}` : ""}`;
91
+ evidence.textContent = app.t(`receiptEvidence_${reader.evidence}`);
92
+ row.dataset.readerSessionId = reader.sessionID;
93
+ row.append(name, evidence); list.append(row);
94
+ }
95
+ }
96
+ function updateButton(button, message, own = button.dataset.ownMessage === "true") {
97
+ const readers = readersFor(message), count = readers.length, known = hasReceiptData(message);
98
+ const label = readerStatus(message, readers);
99
+ button.hidden = !own && count === 0;
100
+ button.textContent = String(count || (known ? 0 : "…"));
101
+ button.dataset.readerState = count ? "read" : known ? "empty" : "unknown";
102
+ button.setAttribute("aria-label", label);
103
+ button.setAttribute("aria-expanded", String(selectedID === message.id));
104
+ button.title = label;
105
+ }
106
+ function readersFor(message) {
107
+ const key = receiptKey(message);
108
+ const senderID = message.senderSessionID || (app.state.room?.kind === "direct" ? message.senderId : "");
109
+ return (app.state.receipts.get(key) || []).filter((reader) => reader.sessionID !== senderID);
110
+ }
111
+ function hasReceiptData(message) { return app.state.receipts.has(receiptKey(message)); }
112
+ function receiptKey(message) { return `${app.state.room?.id || message.roomId || ""}\0${message.id}`; }
113
+ function readerStatus(message, readers) {
114
+ if (readers.length) return app.t("receiptCount", { count: readers.length });
115
+ return app.t(hasReceiptData(message) ? "receiptNone" : "receiptNotLoaded");
116
+ }
117
+ }
@@ -22,6 +22,7 @@ export function initRooms(app) {
22
22
  $("#btnCopyId").title = app.t("copyRoomIdTitle", { id: app.state.room.id });
23
23
  $("#btnCopyId").setAttribute("aria-label", app.t("copyRoomId"));
24
24
  app.setText($("#railIdentity"), "identityLabel", { name: app.state.myName });
25
+ $("#profileAvatar").textContent = Array.from(app.state.myName.trim())[0]?.toLocaleUpperCase() || "?";
25
26
  app.updateTitle();
26
27
  };
27
28
 
@@ -40,6 +41,7 @@ export function initRooms(app) {
40
41
  const entry = existing || { unreadIds: new Map(), unreadOverflow: false, preview: "", previewAt: 0, position: 0, readTs: 0, receivedTs: room.messages.at(-1)?.createdAt ?? 0 };
41
42
  entry.unreadIds ||= new Map();
42
43
  entry.unreadOverflow ||= false;
44
+ entry.readTs ||= app.state.lastReadTs.get(room.id) || 0;
43
45
  entry.room = room;
44
46
  entry.name = name;
45
47
  const latest = room.messages.at(-1);
@@ -60,13 +62,12 @@ export function initRooms(app) {
60
62
  if (app.state.room?.id === roomId) return;
61
63
  if (app.state.room) {
62
64
  app.saveDraft(app.state.room.id, $("#msgInput").value);
63
- app.savePosition(app.state.room.id, $("#thread").scrollTop);
65
+ app.captureReadingPosition?.();
64
66
  }
65
67
  app.stopPolling();
66
68
  app.state.room = entry.room;
67
69
  app.state.myName = entry.name;
68
- const hasSavedPosition = app.state.positions.has(roomId);
69
- entry.position = app.state.positions.get(roomId) ?? entry.position;
70
+ const savedPosition = app.state.positions.get(roomId);
70
71
  app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
71
72
  app.rendered = 0;
72
73
  app.firstMessageId = null;
@@ -76,9 +77,11 @@ export function initRooms(app) {
76
77
  app.renderHead();
77
78
  $("#msgList").textContent = "";
78
79
  app.renderMessages(false);
80
+ const restoredPosition = app.restoreReadingPosition?.(roomId);
81
+ app.state.readAnchorGuard = restoredPosition ? { roomId, ...restoredPosition } : null;
79
82
  app.startPolling();
80
83
  app.renderMembers();
81
- $("#thread").scrollTop = hasSavedPosition ? entry.position : entry.position || $("#thread").scrollHeight;
84
+ if (!restoredPosition) $("#thread").scrollTop = typeof savedPosition === "number" ? savedPosition : entry.position || $("#thread").scrollHeight;
82
85
  $("#msgInput").disabled = false;
83
86
  $("#msgInput").value = app.state.drafts.get(roomId) || "";
84
87
  app.renderFailedMessages();
@@ -88,10 +91,11 @@ export function initRooms(app) {
88
91
  app.hideSendError();
89
92
  app.updateBadge();
90
93
  app.updateJump();
91
- app.markActiveRoomRead();
94
+ if (!restoredPosition) app.markActiveRoomRead();
92
95
  app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
93
96
  app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
94
97
  void app.refreshRoomList();
98
+ document.dispatchEvent(new CustomEvent("chat-room-activated", { detail: roomId }));
95
99
  };
96
100
 
97
101
  app.joinRoom = async (roomId, name) => {
@@ -165,7 +169,7 @@ export function initRooms(app) {
165
169
  if (active) {
166
170
  app.state.navigationGeneration++;
167
171
  app.saveDraft(roomId, $("#msgInput").value);
168
- app.savePosition(roomId, $("#thread").scrollTop);
172
+ app.captureReadingPosition?.();
169
173
  app.stopPolling();
170
174
  app.closeMention();
171
175
  app.state.room = null;
@@ -375,6 +379,7 @@ export function initRooms(app) {
375
379
  app.openTokenBox = () => { $("#tokenBox").open = true; };
376
380
  app.openChatSettings = () => {
377
381
  app.closePanels();
382
+ app.lastFocus = $("#btnSettings");
378
383
  $("#chatSettings").hidden = false;
379
384
  $("#btnSettings").setAttribute("aria-expanded", "true");
380
385
  $("#tokenHint").hidden = false;