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

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 (54) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +23 -7
  3. package/README.zh-CN.md +23 -7
  4. package/docs/administrator-rooms.md +51 -0
  5. package/package.json +11 -2
  6. package/plugin.ts +29 -12
  7. package/server/admin-auth.ts +16 -0
  8. package/server/admin-plan-routes.ts +79 -0
  9. package/server/admin-routes.ts +154 -0
  10. package/server/admin-scheduler.ts +42 -0
  11. package/server/admin-state.ts +61 -0
  12. package/server/admin-task-routes.ts +182 -0
  13. package/server/assets/base.css +55 -43
  14. package/server/assets/chat/admin.js +223 -0
  15. package/server/assets/chat/attachments.js +240 -0
  16. package/server/assets/chat/editor.js +211 -0
  17. package/server/assets/chat/events.js +34 -10
  18. package/server/assets/chat/index.js +8 -0
  19. package/server/assets/chat/markdown.js +1 -12
  20. package/server/assets/chat/members.js +1 -1
  21. package/server/assets/chat/mentions.js +38 -28
  22. package/server/assets/chat/message-window.js +18 -0
  23. package/server/assets/chat/messages.js +64 -46
  24. package/server/assets/chat/questions.js +113 -41
  25. package/server/assets/chat/receipts.js +0 -1
  26. package/server/assets/chat/reminders.js +101 -0
  27. package/server/assets/chat/replies.js +149 -0
  28. package/server/assets/chat/rooms.js +30 -10
  29. package/server/assets/chat/state.js +68 -18
  30. package/server/assets/conversation.css +111 -45
  31. package/server/assets/responsive.css +83 -28
  32. package/server/chat-server.ts +23 -6
  33. package/server/chat.html +82 -31
  34. package/server/inbox.ts +5 -1
  35. package/server/newrooms.ts +27 -10
  36. package/server/resource-routes.ts +3 -0
  37. package/server/room-reminders.ts +212 -0
  38. package/server/wake.ts +11 -15
  39. package/skills/chatroom/SKILL.md +21 -1
  40. package/src/admin-client.ts +130 -0
  41. package/src/admin-credentials.ts +58 -0
  42. package/src/agent-receipts.ts +13 -18
  43. package/src/center-client.ts +1 -1
  44. package/src/center-inbox.ts +2 -0
  45. package/src/plugin-notifications.ts +4 -0
  46. package/src/queue.ts +7 -2
  47. package/src/reminder-client.ts +50 -0
  48. package/src/resource-read.ts +118 -0
  49. package/src/resources.ts +1 -1
  50. package/src/sqlite-state.ts +89 -21
  51. package/src/store.ts +22 -8
  52. package/src/supervision-inbox.ts +62 -0
  53. package/src/v1-plugin.ts +13 -3
  54. package/src/v2-plugin.ts +24 -7
@@ -0,0 +1,211 @@
1
+ import { createRandomId } from "./state.js";
2
+
3
+ const trustedChipNames = new Map();
4
+ function mentionName(node) {
5
+ const name = trustedChipNames.get(node.dataset?.chatChip);
6
+ return name !== undefined && node.dataset.mention === name && node.textContent === `@${name}` ? name : null;
7
+ }
8
+
9
+ export function editorText(editor, draft = false) {
10
+ if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "BR") return "";
11
+ if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "DIV" && editor.firstElementChild?.nodeName === "BR") return "";
12
+ let value = "";
13
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
14
+ const walk = (node) => {
15
+ if (node.nodeType === Node.TEXT_NODE) value += draft ? encodeDraftText(node.nodeValue) : node.nodeValue;
16
+ else if (node.nodeType === Node.ELEMENT_NODE) {
17
+ const mention = mentionName(node);
18
+ if (mention !== null) value += `<at>@${mention}</at>`;
19
+ else if (node.tagName === "BR") value += "\n";
20
+ else node.childNodes.forEach((child, index, all) => {
21
+ if (index && (block(child) || block(all[index - 1]))) value += "\n";
22
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) walk(child);
23
+ });
24
+ }
25
+ };
26
+ editor.childNodes.forEach((node, index, all) => {
27
+ if (index && (block(node) || block(all[index - 1]))) value += "\n";
28
+ if (!(block(node) && node.childNodes.length === 1 && node.firstChild.nodeName === "BR")) walk(node);
29
+ });
30
+ return value;
31
+ }
32
+
33
+ export const editorDraftText = (editor) => editorText(editor, true);
34
+ const literalMention = /<at>@([^<]+)<\/at>/g;
35
+ function encodeDraftText(text) { return String(text).replace(/\uE000/g, "\uE000\uE000").replace(literalMention, "\uE000$&"); }
36
+
37
+ export function setEditorText(editor, value, draft = false) {
38
+ editor.replaceChildren();
39
+ const pattern = draft ? /\uE000\uE000|\uE000<at>@([^<]+)<\/at>|<at>@([^<]+)<\/at>/g : /<at>@([^<]+)<\/at>/g;
40
+ let offset = 0, match;
41
+ while ((match = pattern.exec(String(value))) !== null) {
42
+ editor.append(document.createTextNode(String(value).slice(offset, match.index)));
43
+ if (draft && match[0] === "\uE000\uE000") { editor.append(document.createTextNode("\uE000")); offset = pattern.lastIndex; continue; }
44
+ if (draft && match[0].startsWith("\uE000")) { editor.append(document.createTextNode(match[0].slice(1))); offset = pattern.lastIndex; continue; }
45
+ const chip = document.createElement("span");
46
+ const name = match[draft ? 2 : 1];
47
+ chip.className = "editor-mention"; chip.dataset.mention = name;
48
+ chip.dataset.chatChip = createRandomId(); trustedChipNames.set(chip.dataset.chatChip, name);
49
+ chip.contentEditable = "false"; chip.setAttribute("role", "img");
50
+ chip.setAttribute("aria-label", `Mention ${name}`); chip.textContent = `@${name}`;
51
+ editor.append(chip); offset = pattern.lastIndex;
52
+ }
53
+ editor.append(document.createTextNode(String(value).slice(offset)));
54
+ pruneTrustedChipNames();
55
+ }
56
+
57
+ export function editorSelectionOffsets(editor) {
58
+ const selection = getSelection();
59
+ if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return [editorText(editor).length, editorText(editor).length];
60
+ const selected = selection.getRangeAt(0);
61
+ const offset = (node, position) => lengthBefore(editor, node, position);
62
+ return [offset(selected.startContainer, selected.startOffset), offset(selected.endContainer, selected.endOffset)];
63
+ }
64
+
65
+ function lengthBefore(root, target, position) {
66
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
67
+ const length = (node) => node.nodeType === Node.TEXT_NODE ? node.length
68
+ : mentionName(node) !== null ? `<at>@${mentionName(node)}</at>`.length
69
+ : node.tagName === "BR" ? 1 : childrenLength(node);
70
+ const childrenLength = (parent, until = parent.childNodes.length) => {
71
+ let sum = 0;
72
+ for (let index = 0; index < until; index++) {
73
+ const child = parent.childNodes[index];
74
+ if (index && (block(child) || block(parent.childNodes[index - 1]))) sum++;
75
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) sum += length(child);
76
+ }
77
+ return sum;
78
+ };
79
+ const visit = (node) => {
80
+ if (node === target) return node.nodeType === Node.TEXT_NODE ? Math.min(position, node.length)
81
+ : childrenLength(node, position);
82
+ let total = 0;
83
+ for (let index = 0; index < node.childNodes.length; index++) {
84
+ const child = node.childNodes[index];
85
+ if (index && (block(child) || block(node.childNodes[index - 1]))) total++;
86
+ if (child === target || child.contains(target)) return total + visit(child);
87
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) total += length(child);
88
+ }
89
+ return total;
90
+ };
91
+ return visit(root);
92
+ }
93
+
94
+ export function setCaret(editor, offset) {
95
+ const selection = getSelection(), range = document.createRange(), point = editorPoint(editor, offset);
96
+ range.setStart(point[0], point[1]); range.collapse(true);
97
+ selection.removeAllRanges(); selection.addRange(range);
98
+ }
99
+
100
+ export function setEditorSelection(editor, start, end = start) {
101
+ const range = document.createRange(), selection = getSelection();
102
+ const first = editorPoint(editor, start), last = editorPoint(editor, end);
103
+ range.setStart(first[0], first[1]); range.setEnd(last[0], last[1]);
104
+ selection.removeAllRanges(); selection.addRange(range);
105
+ }
106
+
107
+ function editorPoint(editor, offset) {
108
+ const last = editor.lastElementChild;
109
+ if (offset === editorText(editor).length && editor.lastChild === last && last?.tagName === "DIV" && last.firstChild?.nodeName === "BR") {
110
+ const text = last.appendChild(document.createTextNode("")); return [text, 0];
111
+ }
112
+ if (offset === editorText(editor).length && editor.lastChild?.nodeName === "BR") {
113
+ const text = editor.appendChild(document.createTextNode("")); return [text, 0];
114
+ }
115
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
116
+ let left = offset, point = null;
117
+ const visit = (node) => {
118
+ if (point) return;
119
+ if (node.nodeType === Node.TEXT_NODE) {
120
+ if (left <= node.length) point = [node, left]; else left -= node.length;
121
+ } else if (node.nodeType === Node.ELEMENT_NODE && mentionName(node) !== null) {
122
+ const index = [...node.parentNode.childNodes].indexOf(node), length = `<at>@${mentionName(node)}</at>`.length;
123
+ if (left <= length) point = [node.parentNode, index + (left ? 1 : 0)]; else left -= length;
124
+ } else if (node.tagName === "BR") {
125
+ const index = [...node.parentNode.childNodes].indexOf(node);
126
+ if (left <= 1) point = [node.parentNode, index + (left ? 1 : 0)]; else left--;
127
+ } else node.childNodes.forEach((child, index, all) => {
128
+ if (index && (block(child) || block(all[index - 1]))) {
129
+ if (left === 0) { point = [node, index]; return; }
130
+ left--;
131
+ }
132
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) visit(child);
133
+ });
134
+ };
135
+ visit(editor);
136
+ if (point) return point;
137
+ const node = editor.appendChild(document.createTextNode("")); return [node, 0];
138
+ }
139
+
140
+ export function replaceEditorRange(editor, start, end, value, parseMentions = true) {
141
+ setEditorSelection(editor, start, end);
142
+ if (!parseMentions && document.execCommand("insertText", false, String(value))) return;
143
+ const marker = `chat-insert-${createRandomId()}`;
144
+ const source = String(value), token = parseMentions ? /<at>@([^<]+)<\/at>/g : null;
145
+ let html = "", cursor = 0, match;
146
+ while (token && (match = token.exec(source))) {
147
+ html += textHTML(source.slice(cursor, match.index));
148
+ const name = escapeHTML(match[1]);
149
+ const chipID = createRandomId(); trustedChipNames.set(chipID, match[1]);
150
+ html += `<span class="editor-mention" data-mention="${name}" data-chat-chip="${chipID}" data-insert-marker="${marker}" contenteditable="false" role="img" aria-label="Mention ${name}">@${name}</span>`;
151
+ cursor = token.lastIndex;
152
+ }
153
+ html += textHTML(source.slice(cursor));
154
+ if (document.execCommand("insertHTML", false, html)) {
155
+ editor.querySelectorAll(`[data-insert-marker="${marker}"]`).forEach((chip) => chip.removeAttribute("data-insert-marker"));
156
+ setCaret(editor, start + source.length);
157
+ pruneTrustedChipNames();
158
+ } else {
159
+ const current = editorText(editor), next = current.slice(0, start) + value + current.slice(end);
160
+ if (parseMentions) setEditorText(editor, next); else editor.replaceChildren(document.createTextNode(next));
161
+ setCaret(editor, start + value.length);
162
+ pruneTrustedChipNames();
163
+ }
164
+ }
165
+
166
+ function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]); }
167
+ function textHTML(text) { return escapeHTML(text).replace(/\r\n|\r|\n/g, "<br>"); }
168
+
169
+ function pruneTrustedChipNames() {
170
+ const live = new Set([...document.querySelectorAll("[data-chat-chip]")].map((node) => node.dataset.chatChip));
171
+ const stale = [...trustedChipNames.keys()].filter((id) => !live.has(id));
172
+ // shortcut: retain 2,048 detached IDs for undo history; raise if longer histories are required.
173
+ stale.slice(0, Math.max(0, stale.length - 2048)).forEach((id) => trustedChipNames.delete(id));
174
+ }
175
+
176
+ export function installEditor(editor) {
177
+ Object.defineProperty(editor, "value", {
178
+ get: () => editorText(editor), set: (value) => setEditorText(editor, value),
179
+ });
180
+ Object.defineProperty(editor, "draftValue", {
181
+ get: () => editorDraftText(editor), set: (value) => setEditorText(editor, value, true),
182
+ });
183
+ Object.defineProperties(editor, {
184
+ selectionStart: { get: () => editorSelectionOffsets(editor)[0] },
185
+ selectionEnd: { get: () => editorSelectionOffsets(editor)[1] },
186
+ });
187
+ editor.getSelectionOffsets = () => editorSelectionOffsets(editor);
188
+ editor.setCaret = (offset) => setCaret(editor, offset);
189
+ editor.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
190
+ editor.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
191
+ editor.addEventListener("input", pruneTrustedChipNames);
192
+ editor.addEventListener("paste", (event) => {
193
+ if (event.defaultPrevented || event.clipboardData?.files.length) return;
194
+ event.preventDefault();
195
+ const [start, end] = editorSelectionOffsets(editor);
196
+ replaceEditorRange(editor, start, end, event.clipboardData?.getData("text/plain") || "", false);
197
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromPaste" }));
198
+ });
199
+ editor.addEventListener("drop", (event) => {
200
+ if (event.defaultPrevented || event.dataTransfer?.files.length) return;
201
+ const html = event.dataTransfer?.getData("text/html") || "";
202
+ const text = event.dataTransfer?.getData("text/plain") || new DOMParser().parseFromString(html, "text/html").body.textContent || "";
203
+ if (!text) return;
204
+ event.preventDefault();
205
+ const range = document.caretRangeFromPoint?.(event.clientX, event.clientY), selection = getSelection();
206
+ if (range && editor.contains(range.startContainer)) { selection.removeAllRanges(); selection.addRange(range); }
207
+ const [start, end] = editorSelectionOffsets(editor);
208
+ replaceEditorRange(editor, start, end, text, false);
209
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromDrop" }));
210
+ });
211
+ }
@@ -1,8 +1,16 @@
1
1
  import { LS } from "./state.js";
2
- import { copyCodeFromButton, copyTextToClipboard } from "./markdown.js";
2
+ import { copyTextToClipboard } from "./markdown.js";
3
3
 
4
4
  export function initEvents(app) {
5
5
  const $ = app.$;
6
+ app.showRestoreFailure = (message) => {
7
+ document.documentElement.classList.add("session-restore");
8
+ $("#joinView").hidden = $("#chatView").hidden = true;
9
+ $("#restoreView").hidden = false;
10
+ $("#restoreError").textContent = message;
11
+ $("#restoreError").hidden = false;
12
+ $("#btnRestoreRetry").hidden = false;
13
+ };
6
14
  const roomRail = $("#roomRail"), drawerTrigger = $("#btnRoomsDrawer"), backdrop = $("#roomDrawerBackdrop");
7
15
  const smallScreen = () => matchMedia("(max-width: 760px)").matches;
8
16
  let readingPosition = null, resizeFrame = 0, resizeGeneration = 0, scrollGeneration = 0, resizeResetTimer = 0;
@@ -157,6 +165,16 @@ export function initEvents(app) {
157
165
  $("#btnDeleteRoom").addEventListener("click", () => void app.deleteRoom());
158
166
  $("#btnMembers").addEventListener("click", () => app.togglePanel("#memberPanel"));
159
167
  $("#btnSettings").addEventListener("click", () => app.togglePanel("#chatSettings"));
168
+ $("#btnRoomOptions").addEventListener("click", () => {
169
+ const panel = $("#roomOptions"), open = panel.hidden;
170
+ app.closePanels(); panel.hidden = !open;
171
+ $("#btnRoomOptions").setAttribute("aria-expanded", String(open));
172
+ });
173
+ $("#btnRestoreRetry").addEventListener("click", () => {
174
+ $("#btnRestoreRetry").hidden = true;
175
+ $("#restoreError").hidden = true;
176
+ void app.refreshRoomList();
177
+ });
160
178
  $("#btnRefreshRooms").addEventListener("click", () => void app.refreshRoomList());
161
179
  $("#btnNewRoom").addEventListener("click", () => {
162
180
  const form = $("#railRoomForm");
@@ -175,17 +193,18 @@ export function initEvents(app) {
175
193
  if (failedAction === "retry") void app.retryFailedMessage(failedRoom, failedId);
176
194
  else app.discardFailedMessage(failedRoom, failedId);
177
195
  });
178
- input.addEventListener("input", () => {
196
+ input.addEventListener("input", (event) => {
179
197
  app.autoGrow(input);
180
198
  app.updateSendState();
181
199
  app.updateDraftCount();
182
200
  if (app.state.room) {
183
201
  const id = app.state.room.id;
184
202
  app.state.draftRevision.set(id, (app.state.draftRevision.get(id) || 0) + 1);
185
- app.saveDraft(id, input.value);
203
+ app.saveDraft(id, input.draftValue);
186
204
  }
187
- app.recomputeMention();
205
+ if (!event.isComposing) app.recomputeMention();
188
206
  });
207
+ input.addEventListener("compositionend", () => app.recomputeMention(input));
189
208
  input.addEventListener("keydown", (event) => handleMessageKey(event, app));
190
209
  input.addEventListener("keyup", (event) => {
191
210
  if (app.mentionActive && /^(ArrowLeft|ArrowRight|Home|End)$/.test(event.key)) app.recomputeMention();
@@ -200,7 +219,13 @@ export function initEvents(app) {
200
219
  });
201
220
  const thread = $("#thread");
202
221
  const markScrollIntent = () => { scrollGeneration++; app.state.userScrollIntentUntil = performance.now() + 700; };
203
- thread.addEventListener("wheel", markScrollIntent, { passive: true });
222
+ // Stop wheel overscroll at the ends. Without this, some layouts let the
223
+ // document absorb the leftover delta and the view jumps a few pixels.
224
+ thread.addEventListener("wheel", (event) => {
225
+ markScrollIntent();
226
+ const gap = thread.scrollHeight - thread.clientHeight - thread.scrollTop;
227
+ if (event.deltaY < 0 && thread.scrollTop <= 0 || event.deltaY > 0 && gap <= 2) event.preventDefault();
228
+ }, { passive: false });
204
229
  thread.addEventListener("touchmove", markScrollIntent, { passive: true });
205
230
  thread.addEventListener("pointerdown", (event) => {
206
231
  if (event.clientX >= thread.getBoundingClientRect().right - 18) markScrollIntent();
@@ -225,8 +250,6 @@ export function initEvents(app) {
225
250
  app.queueReceiptRefresh();
226
251
  });
227
252
  $("#msgList").addEventListener("click", (event) => {
228
- const button = event.target.closest("[data-copy-code]");
229
- if (button) void copyCodeFromButton(button, app);
230
253
  const messageButton = event.target.closest("[data-copy-message]");
231
254
  if (messageButton) void copyTextToClipboard(messageButton._copyText).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
232
255
  });
@@ -273,7 +296,7 @@ export function initEvents(app) {
273
296
  $("#inToken").value = LS.token;
274
297
  $("#inTokenChat").value = LS.token;
275
298
  void app.refreshRoomList();
276
- $("#inRoomId").focus();
299
+ if (!$("#joinView").hidden) $("#inRoomId").focus();
277
300
  }
278
301
 
279
302
  async function loadAnchorHistory(roomId, entry, messageId, app, readTs = 0, signal) {
@@ -308,7 +331,8 @@ function saveAccessToken(button, app) {
308
331
  }
309
332
 
310
333
  function handleMessageKey(event, app) {
311
- if (app.mentionActive && !event.isComposing) {
334
+ if (app.handleMentionKey(event, event.currentTarget)) return;
335
+ if (app.mentionActive && !event.isComposing && event.keyCode !== 229) {
312
336
  if (event.key === "ArrowDown") { event.preventDefault(); app.moveMention(1); return; }
313
337
  if (event.key === "ArrowUp") { event.preventDefault(); app.moveMention(-1); return; }
314
338
  if (event.key === "Escape") { event.preventDefault(); app.closeMention(); return; }
@@ -322,7 +346,7 @@ function handleMessageKey(event, app) {
322
346
  if (event.key === "Tab") return;
323
347
  }
324
348
  }
325
- if (event.key === "Enter" && !event.isComposing && (event.ctrlKey || !event.shiftKey)) {
349
+ if (event.key === "Enter" && !event.isComposing && event.keyCode !== 229 && (event.ctrlKey || !event.shiftKey)) {
326
350
  event.preventDefault();
327
351
  void app.send();
328
352
  }
@@ -7,12 +7,20 @@ import { initEvents } from "./events.js";
7
7
  import { initQuestions } from "./questions.js";
8
8
  import { initReceipts } from "./receipts.js";
9
9
  import { initAnnouncements } from "./announcements.js";
10
+ import { initAdmin } from "./admin.js";
11
+ import { initAttachments } from "./attachments.js";
12
+ import { initReplies } from "./replies.js";
13
+ import { initReminders } from "./reminders.js";
10
14
 
11
15
  initMentions(app);
12
16
  initMessages(app);
17
+ initAttachments(app);
13
18
  initReceipts(app);
14
19
  initMembers(app);
15
20
  initRooms(app);
16
21
  initQuestions(app);
22
+ initReplies(app);
17
23
  initEvents(app);
18
24
  initAnnouncements(app);
25
+ initReminders(app);
26
+ initAdmin(app);
@@ -37,7 +37,6 @@ export function renderMarkdown(root, text, app) {
37
37
  link.rel = "noopener noreferrer";
38
38
  });
39
39
  fragment.querySelectorAll('input[type="checkbox"]').forEach((input) => { input.disabled = true; });
40
- fragment.querySelectorAll("pre").forEach((pre) => addCodeCopy(pre, app));
41
40
  root.appendChild(fragment);
42
41
  for (let i = 0; i < diagramNodes.length; i++) {
43
42
  const source = diagrams.get(`CHATDIAGRAM${nonce}${i}END`);
@@ -92,14 +91,9 @@ function showDiagramFallback(node, source, app, loading) {
92
91
  node.append(status);
93
92
  if (!loading) {
94
93
  const pre = document.createElement("pre"), code = document.createElement("code");
95
- code.textContent = source; pre.append(code); addCodeCopy(pre, app); node.append(pre);
94
+ code.textContent = source; pre.append(code); node.append(pre);
96
95
  }
97
96
  }
98
- function addCodeCopy(pre, app) {
99
- const button = document.createElement("button");
100
- button.type = "button"; button.className = "code-copy"; button.dataset.copyCode = "";
101
- button.dataset.i18n = "copyCode"; button.textContent = app.t("copyCode"); pre.append(button);
102
- }
103
97
 
104
98
  function replaceResourceMarkers(fragment, app) {
105
99
  const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_TEXT), nodes = [], cards = [], roomId = app.state.room?.id;
@@ -259,11 +253,6 @@ function replaceMentionTokens(fragment, mentions, app) {
259
253
  }
260
254
  }
261
255
 
262
- export function copyCodeFromButton(button, app) {
263
- const code = button.parentElement.querySelector("code")?.textContent || "";
264
- return copyTextToClipboard(code).then((copied) => copied ? app.flash(button, "copiedCode") : app.showSendError("copyCodeFailed"));
265
- }
266
-
267
256
  export async function copyTextToClipboard(text) {
268
257
  try {
269
258
  if (navigator.clipboard?.writeText) {
@@ -12,7 +12,7 @@ export function initMembers(app) {
12
12
 
13
13
  app.renderMembers = () => {
14
14
  const people = app.state.room?.participants || [];
15
- app.setText($("#btnMembers"), "membersCount", { count: people.length });
15
+ app.setText($("#btnMembers .action-label"), "membersCount", { count: people.length });
16
16
  const list = $("#memberList");
17
17
  list.textContent = "";
18
18
  for (const person of people) {
@@ -1,6 +1,8 @@
1
+ import { editorSelectionOffsets, replaceEditorRange } from "./editor.js";
2
+
1
3
  export function initMentions(app) {
2
4
  const $ = app.$;
3
- const mention = { active: false, start: 0, query: "", items: [], index: 0 };
5
+ const mention = { active: false, start: 0, query: "", items: [], index: 0, editor: null };
4
6
  app.mention = mention;
5
7
  app.mentionActive = false;
6
8
  app.updateMentionList = (query = mention.query) => {
@@ -25,50 +27,57 @@ export function initMentions(app) {
25
27
  highlightMention(app, mention);
26
28
  };
27
29
 
28
- app.openMention = (start, query) => {
30
+ app.openMention = (start, query, input = $("#msgInput")) => {
29
31
  mention.active = app.mentionActive = true;
32
+ mention.editor = input;
30
33
  mention.start = start;
31
34
  app.updateMentionList(query);
32
- $("#mentionPicker").hidden = false;
33
- $("#msgInput").setAttribute("aria-expanded", "true");
35
+ const picker = $("#mentionPicker"); picker.hidden = false;
36
+ if (input.id !== "msgInput") {
37
+ const rect = input.getBoundingClientRect();
38
+ Object.assign(picker.style, { position: "fixed", left: `${rect.left}px`, right: `${innerWidth - rect.right}px`, bottom: `${innerHeight - rect.top + 8}px` });
39
+ }
40
+ input.setAttribute("aria-expanded", "true");
34
41
  };
35
42
  app.closeMention = () => {
36
43
  mention.active = app.mentionActive = false;
37
44
  mention.items = [];
38
- $("#mentionPicker").hidden = true;
39
- $("#msgInput").setAttribute("aria-expanded", "false");
40
- $("#msgInput").removeAttribute("aria-activedescendant");
45
+ mention.editor?.setAttribute("aria-expanded", "false");
46
+ mention.editor?.removeAttribute("aria-activedescendant"); mention.editor = null;
47
+ const picker = $("#mentionPicker"); picker.hidden = true; picker.removeAttribute("style");
41
48
  };
42
49
 
43
- app.recomputeMention = () => {
44
- const input = $("#msgInput"), match = currentMention(input);
50
+ app.recomputeMention = (input = $("#msgInput")) => {
51
+ if (!(input instanceof HTMLElement)) input = $("#msgInput");
52
+ if (mention.active && mention.editor !== input) app.closeMention();
53
+ const match = currentMention(input);
45
54
  if (match) {
46
- mention.active ? app.updateMentionList(match.query) : app.openMention(match.start, match.query);
47
- } else if (mention.active) {
48
- const at = input.value.lastIndexOf("@");
49
- if (at < 0) return app.closeMention();
50
- mention.start = at;
51
- app.updateMentionList(input.value.slice(at + 1, input.selectionStart));
52
- }
55
+ mention.active ? app.updateMentionList(match.query) : app.openMention(match.start, match.query, input);
56
+ } else if (mention.active) app.closeMention();
53
57
  };
54
58
  app.moveMention = (direction) => {
55
59
  if (!mention.items.length) return;
56
60
  mention.index = (mention.index + direction + mention.items.length) % mention.items.length;
57
61
  highlightMention(app, mention);
58
62
  };
63
+ app.handleMentionKey = (event, input) => {
64
+ if (!mention.active || mention.editor !== input || event.isComposing || event.keyCode === 229) return false;
65
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
66
+ event.preventDefault(); app.moveMention(event.key === "ArrowDown" ? 1 : -1); return true;
67
+ }
68
+ if (event.key === "Escape") { event.preventDefault(); app.closeMention(); return true; }
69
+ if (event.key === "Enter" || event.key === "Tab") {
70
+ if (mention.items.length) { event.preventDefault(); app.insertMention(mention.items[mention.index]); return true; }
71
+ app.closeMention(); return event.key === "Tab";
72
+ }
73
+ return false;
74
+ };
59
75
  app.insertMention = (name) => {
60
- const input = $("#msgInput"), end = mention.start + 1 + mention.query.length;
76
+ const input = mention.editor || $("#msgInput"), end = mention.start + 1 + mention.query.length;
61
77
  if (input.value.slice(mention.start, end) !== `@${mention.query}`) return app.closeMention();
62
- input.setRangeText(`<at>@${name}</at>`, mention.start, end, "end");
78
+ replaceEditorRange(input, mention.start, end, `<at>@${name}</at>`);
63
79
  app.closeMention();
64
- app.autoGrow(input);
65
- app.updateSendState();
66
- app.updateDraftCount();
67
- if (app.state.room) {
68
- const id = app.state.room.id;
69
- app.state.draftRevision.set(id, (app.state.draftRevision.get(id) || 0) + 1);
70
- app.saveDraft(id, input.value);
71
- }
80
+ input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" }));
72
81
  input.focus({ preventScroll: true });
73
82
  };
74
83
  }
@@ -109,7 +118,8 @@ function createOption(name, index, query, app) {
109
118
  }
110
119
 
111
120
  function currentMention(input) {
112
- const position = input.selectionStart, value = input.value;
121
+ const [position, end] = editorSelectionOffsets(input), value = input.value;
122
+ if (position !== end) return null;
113
123
  let start = position;
114
124
  while (start > 0 && /[\p{L}\p{N}_]/u.test(value[start - 1])) start--;
115
125
  const at = start - 1;
@@ -120,7 +130,7 @@ function currentMention(input) {
120
130
  }
121
131
 
122
132
  function highlightMention(app, mention) {
123
- const input = app.$("#msgInput"), options = app.$("#mentionPicker").querySelectorAll(".mention-opt");
133
+ const input = mention.editor || app.$("#msgInput"), options = app.$("#mentionPicker").querySelectorAll(".mention-opt");
124
134
  options.forEach((option, index) => {
125
135
  option.classList.toggle("active", index === mention.index);
126
136
  option.setAttribute("aria-selected", String(index === mention.index));
@@ -11,3 +11,21 @@ export function hasMessageSelection(list) {
11
11
  return Boolean(selection && !selection.isCollapsed
12
12
  && (list.contains(selection.anchorNode) || list.contains(selection.focusNode)));
13
13
  }
14
+
15
+ export function trimMessages(list, app) {
16
+ if (list.children.length <= 400 || hasMessageSelection(list)) return;
17
+ const saved = app.state.positions.get(app.state.room?.id), rows = [...list.querySelectorAll("[data-msg-id]")];
18
+ const anchor = saved?.messageId && rows.find((row) => row.dataset.msgId === saved.messageId);
19
+ if (anchor && rows.indexOf(anchor) < rows.length - 280) {
20
+ const recent = rows.at(-300);
21
+ while (list.firstElementChild && list.firstElementChild !== anchor) list.firstElementChild.remove();
22
+ let next = anchor.nextElementSibling;
23
+ while (next && next !== recent) { const after = next.nextElementSibling; next.remove(); next = after; }
24
+ const gap = document.createElement("li"); gap.className = "gap"; app.setText(gap, "messagesBetweenOmitted"); anchor.after(gap);
25
+ return;
26
+ }
27
+ while (list.children.length > 300) list.removeChild(list.firstChild);
28
+ if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
29
+ const gap = document.createElement("li"); gap.className = "gap"; app.setText(gap, "earlierMessages"); list.insertBefore(gap, list.firstChild);
30
+ }
31
+ }