@alexsun-top/opencode-chat-room 0.5.1 → 0.5.3

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 (49) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +28 -207
  3. package/README.zh-CN.md +27 -201
  4. package/docs/administrator-rooms.md +6 -22
  5. package/package.json +4 -5
  6. package/plugin.ts +19 -4
  7. package/server/admin-routes.ts +2 -11
  8. package/server/admin-state.ts +15 -4
  9. package/server/assets/base.css +10 -0
  10. package/server/assets/chat/admin.js +67 -128
  11. package/server/assets/chat/attachments.js +1 -1
  12. package/server/assets/chat/editor.js +248 -0
  13. package/server/assets/chat/events.js +13 -11
  14. package/server/assets/chat/index.js +4 -0
  15. package/server/assets/chat/mentions.js +38 -28
  16. package/server/assets/chat/message-window.js +18 -0
  17. package/server/assets/chat/messages.js +49 -57
  18. package/server/assets/chat/questions.js +115 -43
  19. package/server/assets/chat/receipts.js +0 -1
  20. package/server/assets/chat/reminders.js +102 -0
  21. package/server/assets/chat/replies.js +150 -0
  22. package/server/assets/chat/room-watcher.js +37 -0
  23. package/server/assets/chat/rooms.js +59 -70
  24. package/server/assets/chat/state.js +29 -9
  25. package/server/assets/conversation.css +33 -9
  26. package/server/assets/responsive.css +15 -16
  27. package/server/chat-server.ts +21 -2
  28. package/server/chat.html +23 -13
  29. package/server/inbox.ts +5 -1
  30. package/server/room-reminders.ts +222 -0
  31. package/server/wake.ts +6 -3
  32. package/skills/chatroom/SKILL.md +11 -7
  33. package/src/admin-client.ts +6 -43
  34. package/src/admin-credentials.ts +0 -19
  35. package/src/agent-receipts.ts +13 -18
  36. package/src/mentions.ts +2 -1
  37. package/src/plugin-notifications.ts +4 -0
  38. package/src/queue.ts +7 -2
  39. package/src/reminder-client.ts +50 -0
  40. package/src/resource-read.ts +118 -0
  41. package/src/resource-upload.ts +1 -1
  42. package/src/resources.ts +1 -1
  43. package/src/sqlite-state.ts +43 -3
  44. package/src/store.ts +22 -8
  45. package/src/supervision-inbox.ts +6 -18
  46. package/src/v2-plugin.ts +11 -5
  47. package/server/admin-plan-routes.ts +0 -79
  48. package/server/admin-scheduler.ts +0 -42
  49. package/server/admin-task-routes.ts +0 -182
@@ -0,0 +1,248 @@
1
+ import { createRandomId } from "./state.js";
2
+
3
+ const trustedChipNames = new Map();
4
+ const autoSeparator = "\uE000\uE001";
5
+ function mentionName(node) {
6
+ const name = trustedChipNames.get(node.dataset?.chatChip);
7
+ return name !== undefined && node.dataset.mention === name && node.textContent === `@${name}` ? name : null;
8
+ }
9
+
10
+ export function editorText(editor, draft = false) {
11
+ if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "BR") return "";
12
+ if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "DIV" && editor.firstElementChild?.nodeName === "BR") return "";
13
+ let value = "";
14
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
15
+ const walk = (node) => {
16
+ if (node.nodeType === Node.TEXT_NODE) value += draft ? encodeDraftText(node.nodeValue) : node.nodeValue;
17
+ else if (node.nodeType === Node.ELEMENT_NODE) {
18
+ const mention = mentionName(node);
19
+ if (node.dataset?.chatAutoSeparator) value += draft && node.textContent.startsWith(" ")
20
+ ? autoSeparator + encodeDraftText(node.textContent.slice(1)) : draft ? encodeDraftText(node.textContent) : node.textContent;
21
+ else if (mention !== null) value += `<at>@${mention}</at>`;
22
+ else if (node.tagName === "BR") value += "\n";
23
+ else node.childNodes.forEach((child, index, all) => {
24
+ if (index && (block(child) || block(all[index - 1]))) value += "\n";
25
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) walk(child);
26
+ });
27
+ }
28
+ };
29
+ editor.childNodes.forEach((node, index, all) => {
30
+ if (index && (block(node) || block(all[index - 1]))) value += "\n";
31
+ if (!(block(node) && node.childNodes.length === 1 && node.firstChild.nodeName === "BR")) walk(node);
32
+ });
33
+ return value;
34
+ }
35
+
36
+ export const editorDraftText = (editor) => editorText(editor, true);
37
+ export const autoMentionDraft = (name) => `<at>@${name}</at>${autoSeparator}`;
38
+ const literalMention = /<at>@([^<]+)<\/at>/g;
39
+ function encodeDraftText(text) { return String(text).replace(/\uE000/g, "\uE000\uE000").replace(literalMention, "\uE000$&"); }
40
+
41
+ export function setEditorText(editor, value, draft = false) {
42
+ editor.replaceChildren();
43
+ const pattern = draft ? /\uE000\uE001|\uE000\uE000|\uE000<at>@([^<]+)<\/at>|<at>@([^<]+)<\/at>/g : /<at>@([^<]+)<\/at>/g;
44
+ let offset = 0, match;
45
+ while ((match = pattern.exec(String(value))) !== null) {
46
+ editor.append(document.createTextNode(String(value).slice(offset, match.index)));
47
+ if (draft && match[0] === autoSeparator) { editor.append(createAutoSeparator()); offset = pattern.lastIndex; continue; }
48
+ if (draft && match[0] === "\uE000\uE000") { editor.append(document.createTextNode("\uE000")); offset = pattern.lastIndex; continue; }
49
+ if (draft && match[0].startsWith("\uE000")) { editor.append(document.createTextNode(match[0].slice(1))); offset = pattern.lastIndex; continue; }
50
+ editor.append(createMention(draft ? match[2] : match[1])); offset = pattern.lastIndex;
51
+ }
52
+ editor.append(document.createTextNode(String(value).slice(offset)));
53
+ pruneTrustedChipNames();
54
+ }
55
+
56
+ export function editorSelectionOffsets(editor) {
57
+ const selection = getSelection();
58
+ if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return [editorText(editor).length, editorText(editor).length];
59
+ const selected = selection.getRangeAt(0);
60
+ const offset = (node, position) => lengthBefore(editor, node, position);
61
+ return [offset(selected.startContainer, selected.startOffset), offset(selected.endContainer, selected.endOffset)];
62
+ }
63
+
64
+ function lengthBefore(root, target, position) {
65
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
66
+ const length = (node) => node.nodeType === Node.TEXT_NODE ? node.length
67
+ : mentionName(node) !== null ? `<at>@${mentionName(node)}</at>`.length
68
+ : node.tagName === "BR" ? 1 : childrenLength(node);
69
+ const childrenLength = (parent, until = parent.childNodes.length) => {
70
+ let sum = 0;
71
+ for (let index = 0; index < until; index++) {
72
+ const child = parent.childNodes[index];
73
+ if (index && (block(child) || block(parent.childNodes[index - 1]))) sum++;
74
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) sum += length(child);
75
+ }
76
+ return sum;
77
+ };
78
+ const visit = (node) => {
79
+ if (node === target) return node.nodeType === Node.TEXT_NODE ? Math.min(position, node.length)
80
+ : childrenLength(node, position);
81
+ let total = 0;
82
+ for (let index = 0; index < node.childNodes.length; index++) {
83
+ const child = node.childNodes[index];
84
+ if (index && (block(child) || block(node.childNodes[index - 1]))) total++;
85
+ if (child === target || child.contains(target)) return total + visit(child);
86
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) total += length(child);
87
+ }
88
+ return total;
89
+ };
90
+ return visit(root);
91
+ }
92
+
93
+ export function setCaret(editor, offset) {
94
+ const selection = getSelection(), range = document.createRange(), point = editorPoint(editor, offset);
95
+ range.setStart(point[0], point[1]); range.collapse(true);
96
+ selection.removeAllRanges(); selection.addRange(range);
97
+ }
98
+
99
+ export function setEditorSelection(editor, start, end = start) {
100
+ const range = document.createRange(), selection = getSelection();
101
+ const first = editorPoint(editor, start), last = editorPoint(editor, end);
102
+ range.setStart(first[0], first[1]); range.setEnd(last[0], last[1]);
103
+ selection.removeAllRanges(); selection.addRange(range);
104
+ }
105
+
106
+ function editorPoint(editor, offset) {
107
+ const last = editor.lastElementChild;
108
+ if (offset === editorText(editor).length && editor.lastChild === last && last?.tagName === "DIV" && last.firstChild?.nodeName === "BR") {
109
+ const text = last.appendChild(document.createTextNode("")); return [text, 0];
110
+ }
111
+ if (offset === editorText(editor).length && editor.lastChild?.nodeName === "BR") {
112
+ const text = editor.appendChild(document.createTextNode("")); return [text, 0];
113
+ }
114
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
115
+ let left = offset, point = null;
116
+ const visit = (node) => {
117
+ if (point) return;
118
+ if (node.nodeType === Node.TEXT_NODE) {
119
+ if (left <= node.length) point = [node, left]; else left -= node.length;
120
+ } else if (node.nodeType === Node.ELEMENT_NODE && mentionName(node) !== null) {
121
+ const index = [...node.parentNode.childNodes].indexOf(node), length = `<at>@${mentionName(node)}</at>`.length;
122
+ if (left <= length) point = [node.parentNode, index + (left ? 1 : 0)]; else left -= length;
123
+ } else if (node.tagName === "BR") {
124
+ const index = [...node.parentNode.childNodes].indexOf(node);
125
+ if (left <= 1) point = [node.parentNode, index + (left ? 1 : 0)]; else left--;
126
+ } else node.childNodes.forEach((child, index, all) => {
127
+ if (index && (block(child) || block(all[index - 1]))) {
128
+ if (left === 0) { point = [node, index]; return; }
129
+ left--;
130
+ }
131
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) visit(child);
132
+ });
133
+ };
134
+ visit(editor);
135
+ if (point) return point;
136
+ const node = editor.appendChild(document.createTextNode("")); return [node, 0];
137
+ }
138
+
139
+ export function replaceEditorRange(editor, start, end, value, parseMentions = true) {
140
+ setEditorSelection(editor, start, end);
141
+ if (!parseMentions && document.execCommand("insertText", false, String(value))) return;
142
+ const marker = `chat-insert-${createRandomId()}`;
143
+ const source = String(value), generatedSpace = parseMentions && source.endsWith(" "), content = generatedSpace ? source.slice(0, -1) : source;
144
+ const token = parseMentions ? /<at>@([^<]+)<\/at>/g : null;
145
+ let html = "", cursor = 0, match;
146
+ while (token && (match = token.exec(content))) {
147
+ html += textHTML(content.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(content.slice(cursor));
154
+ if (generatedSpace) html += `<span data-chat-auto-separator="true"> </span>`;
155
+ if (document.execCommand("insertHTML", false, html)) {
156
+ editor.querySelectorAll(`[data-insert-marker="${marker}"]`).forEach((chip) => chip.removeAttribute("data-insert-marker"));
157
+ setCaret(editor, start + source.length);
158
+ pruneTrustedChipNames();
159
+ } else {
160
+ const current = editorText(editor), next = current.slice(0, start) + value + current.slice(end);
161
+ if (parseMentions) setEditorText(editor, next); else editor.replaceChildren(document.createTextNode(next));
162
+ if (generatedSpace) wrapAutoSeparator(editor, start + source.length - 1);
163
+ setCaret(editor, start + value.length);
164
+ pruneTrustedChipNames();
165
+ }
166
+ }
167
+
168
+ function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]); }
169
+ function textHTML(text) { return escapeHTML(text).replace(/\r\n|\r|\n/g, "<br>"); }
170
+
171
+ function createMention(name) {
172
+ const chip = document.createElement("span");
173
+ chip.className = "editor-mention"; chip.dataset.mention = name;
174
+ chip.dataset.chatChip = createRandomId(); trustedChipNames.set(chip.dataset.chatChip, name);
175
+ chip.contentEditable = "false"; chip.setAttribute("role", "img");
176
+ chip.setAttribute("aria-label", `Mention ${name}`); chip.textContent = `@${name}`;
177
+ return chip;
178
+ }
179
+ function createAutoSeparator() {
180
+ const separator = document.createElement("span");
181
+ separator.dataset.chatAutoSeparator = "true"; separator.textContent = " ";
182
+ return separator;
183
+ }
184
+ function wrapAutoSeparator(editor, offset) {
185
+ const start = editorPoint(editor, offset), end = editorPoint(editor, offset + 1), range = document.createRange();
186
+ range.setStart(start[0], start[1]); range.setEnd(end[0], end[1]); range.deleteContents(); range.insertNode(createAutoSeparator());
187
+ }
188
+
189
+ function deleteMentionAtCaret(editor, event) {
190
+ if (event.isComposing || event.keyCode === 229 || event.key !== "Backspace") return;
191
+ const [caret, end] = editorSelectionOffsets(editor);
192
+ if (caret !== end) return;
193
+ const separator = [...editor.querySelectorAll("[data-chat-auto-separator]")].find((node) => {
194
+ const start = lengthBefore(editor, node, 0); return node.textContent === " " && caret === start + 1;
195
+ });
196
+ const mention = separator?.previousElementSibling || [...editor.querySelectorAll(".editor-mention")].find((node) => {
197
+ return caret === lengthBefore(editor, node, 0) + `<at>@${mentionName(node)}</at>`.length;
198
+ });
199
+ if (!mention || (separator && separator.previousElementSibling !== mention)) return;
200
+ const start = lengthBefore(editor, mention, 0);
201
+ event.preventDefault(); mention.remove(); separator?.remove(); setCaret(editor, start);
202
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
203
+ }
204
+
205
+ function pruneTrustedChipNames() {
206
+ const live = new Set([...document.querySelectorAll("[data-chat-chip]")].map((node) => node.dataset.chatChip));
207
+ const stale = [...trustedChipNames.keys()].filter((id) => !live.has(id));
208
+ // shortcut: retain 2,048 detached IDs for undo history; raise if longer histories are required.
209
+ stale.slice(0, Math.max(0, stale.length - 2048)).forEach((id) => trustedChipNames.delete(id));
210
+ }
211
+
212
+ export function installEditor(editor) {
213
+ Object.defineProperty(editor, "value", {
214
+ get: () => editorText(editor), set: (value) => setEditorText(editor, value),
215
+ });
216
+ Object.defineProperty(editor, "draftValue", {
217
+ get: () => editorDraftText(editor), set: (value) => setEditorText(editor, value, true),
218
+ });
219
+ Object.defineProperties(editor, {
220
+ selectionStart: { get: () => editorSelectionOffsets(editor)[0] },
221
+ selectionEnd: { get: () => editorSelectionOffsets(editor)[1] },
222
+ });
223
+ editor.getSelectionOffsets = () => editorSelectionOffsets(editor);
224
+ editor.setCaret = (offset) => setCaret(editor, offset);
225
+ editor.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
226
+ editor.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
227
+ editor.addEventListener("input", pruneTrustedChipNames);
228
+ editor.addEventListener("keydown", (event) => deleteMentionAtCaret(editor, event));
229
+ editor.addEventListener("paste", (event) => {
230
+ if (event.defaultPrevented || event.clipboardData?.files.length) return;
231
+ event.preventDefault();
232
+ const [start, end] = editorSelectionOffsets(editor);
233
+ replaceEditorRange(editor, start, end, event.clipboardData?.getData("text/plain") || "", false);
234
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromPaste" }));
235
+ });
236
+ editor.addEventListener("drop", (event) => {
237
+ if (event.defaultPrevented || event.dataTransfer?.files.length) return;
238
+ const html = event.dataTransfer?.getData("text/html") || "";
239
+ const text = event.dataTransfer?.getData("text/plain") || new DOMParser().parseFromString(html, "text/html").body.textContent || "";
240
+ if (!text) return;
241
+ event.preventDefault();
242
+ const range = document.caretRangeFromPoint?.(event.clientX, event.clientY), selection = getSelection();
243
+ if (range && editor.contains(range.startContainer)) { selection.removeAllRanges(); selection.addRange(range); }
244
+ const [start, end] = editorSelectionOffsets(editor);
245
+ replaceEditorRange(editor, start, end, text, false);
246
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromDrop" }));
247
+ });
248
+ }
@@ -121,24 +121,24 @@ export function initEvents(app) {
121
121
  if (app.state.room?.id === roomId) cancelAnchorLoads();
122
122
  return removeJoinedRoom(roomId, options);
123
123
  };
124
- function activateNow(id) {
125
- activateRoom(id); captureReadingPosition();
124
+ function activateNow(id, preserveRoomListGeneration = false) {
125
+ activateRoom(id, preserveRoomListGeneration); captureReadingPosition();
126
126
  if (roomRail.classList.contains("drawer-open")) closeRoomDrawer();
127
127
  }
128
- app.activateRoom = (id) => {
128
+ app.activateRoom = (id, preserveRoomListGeneration = false) => {
129
129
  cancelAnchorLoads();
130
130
  const entry = app.state.rooms.get(id), saved = app.state.positions.get(id);
131
131
  const intent = ++app.state.navigationGeneration;
132
- if (!entry) return activateNow(id);
132
+ if (!entry) return activateNow(id, preserveRoomListGeneration);
133
133
  const readTs = entry.readTs || app.state.lastReadTs.get(id) || 0;
134
134
  const needAnchor = saved?.messageId && !entry.room.messages.some((message) => message.id === saved.messageId);
135
135
  const latest = entry.room.messages.at(-1);
136
136
  const needBoundary = !saved?.messageId && readTs && (!latest || latest.createdAt > readTs && !entry.room.messages.some((message) => message.createdAt <= readTs));
137
- if (!needAnchor && !needBoundary) return activateNow(id);
137
+ if (!needAnchor && !needBoundary) return activateNow(id, preserveRoomListGeneration);
138
138
  const controller = new AbortController();
139
139
  const task = loadAnchorHistory(id, entry, saved?.messageId, app, needBoundary ? readTs : 0, controller.signal).catch(() => {}).finally(() => {
140
140
  if (pendingAnchorLoads.get(id)?.controller === controller) pendingAnchorLoads.delete(id);
141
- if (intent === app.state.navigationGeneration) activateNow(id);
141
+ if (intent === app.state.navigationGeneration) activateNow(id, preserveRoomListGeneration);
142
142
  });
143
143
  pendingAnchorLoads.set(id, { controller, task });
144
144
  };
@@ -193,17 +193,18 @@ export function initEvents(app) {
193
193
  if (failedAction === "retry") void app.retryFailedMessage(failedRoom, failedId);
194
194
  else app.discardFailedMessage(failedRoom, failedId);
195
195
  });
196
- input.addEventListener("input", () => {
196
+ input.addEventListener("input", (event) => {
197
197
  app.autoGrow(input);
198
198
  app.updateSendState();
199
199
  app.updateDraftCount();
200
200
  if (app.state.room) {
201
201
  const id = app.state.room.id;
202
202
  app.state.draftRevision.set(id, (app.state.draftRevision.get(id) || 0) + 1);
203
- app.saveDraft(id, input.value);
203
+ app.saveDraft(id, input.draftValue);
204
204
  }
205
- app.recomputeMention();
205
+ if (!event.isComposing) app.recomputeMention();
206
206
  });
207
+ input.addEventListener("compositionend", () => app.recomputeMention(input));
207
208
  input.addEventListener("keydown", (event) => handleMessageKey(event, app));
208
209
  input.addEventListener("keyup", (event) => {
209
210
  if (app.mentionActive && /^(ArrowLeft|ArrowRight|Home|End)$/.test(event.key)) app.recomputeMention();
@@ -330,7 +331,8 @@ function saveAccessToken(button, app) {
330
331
  }
331
332
 
332
333
  function handleMessageKey(event, app) {
333
- if (app.mentionActive && !event.isComposing) {
334
+ if (app.handleMentionKey(event, event.currentTarget)) return;
335
+ if (app.mentionActive && !event.isComposing && event.keyCode !== 229) {
334
336
  if (event.key === "ArrowDown") { event.preventDefault(); app.moveMention(1); return; }
335
337
  if (event.key === "ArrowUp") { event.preventDefault(); app.moveMention(-1); return; }
336
338
  if (event.key === "Escape") { event.preventDefault(); app.closeMention(); return; }
@@ -344,7 +346,7 @@ function handleMessageKey(event, app) {
344
346
  if (event.key === "Tab") return;
345
347
  }
346
348
  }
347
- if (event.key === "Enter" && !event.isComposing && (event.ctrlKey || !event.shiftKey)) {
349
+ if (event.key === "Enter" && !event.isComposing && event.keyCode !== 229 && (event.ctrlKey || !event.shiftKey)) {
348
350
  event.preventDefault();
349
351
  void app.send();
350
352
  }
@@ -9,6 +9,8 @@ import { initReceipts } from "./receipts.js";
9
9
  import { initAnnouncements } from "./announcements.js";
10
10
  import { initAdmin } from "./admin.js";
11
11
  import { initAttachments } from "./attachments.js";
12
+ import { initReplies } from "./replies.js";
13
+ import { initReminders } from "./reminders.js";
12
14
 
13
15
  initMentions(app);
14
16
  initMessages(app);
@@ -17,6 +19,8 @@ initReceipts(app);
17
19
  initMembers(app);
18
20
  initRooms(app);
19
21
  initQuestions(app);
22
+ initReplies(app);
20
23
  initEvents(app);
21
24
  initAnnouncements(app);
25
+ initReminders(app);
22
26
  initAdmin(app);
@@ -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
+ }