@alexsun-top/opencode-chat-room 0.8.3 → 0.8.4

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 (56) hide show
  1. package/CHANGELOG.md +3 -1
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +4 -4
  4. package/package.json +6 -3
  5. package/server/assets/chat/admin-badge.js +1 -1
  6. package/server/assets/chat/admin.js +12 -9
  7. package/server/assets/chat/announcements.js +9 -2
  8. package/server/assets/chat/attachment-store.js +15 -6
  9. package/server/assets/chat/attachments.js +46 -31
  10. package/server/assets/chat/chat-background.js +8 -14
  11. package/server/assets/chat/clipboard.js +2 -1
  12. package/server/assets/chat/confirm-dialog.js +3 -3
  13. package/server/assets/chat/copy-action.js +0 -1
  14. package/server/assets/chat/diagram-viewer.js +7 -9
  15. package/server/assets/chat/doc-preview.js +18 -11
  16. package/server/assets/chat/editor.js +80 -58
  17. package/server/assets/chat/events.js +43 -30
  18. package/server/assets/chat/files.js +41 -13
  19. package/server/assets/chat/history-loader.js +5 -3
  20. package/server/assets/chat/image-zoom.js +21 -17
  21. package/server/assets/chat/install-prompt.js +10 -9
  22. package/server/assets/chat/integration-account-schema.js +5 -3
  23. package/server/assets/chat/integration-editor.js +0 -2
  24. package/server/assets/chat/integration-values.js +17 -11
  25. package/server/assets/chat/integrations.js +137 -80
  26. package/server/assets/chat/join-requests.js +19 -12
  27. package/server/assets/chat/markdown-footnotes.js +0 -1
  28. package/server/assets/chat/markdown.js +43 -34
  29. package/server/assets/chat/members.js +45 -22
  30. package/server/assets/chat/mentions.js +31 -7
  31. package/server/assets/chat/message-cache.js +1 -1
  32. package/server/assets/chat/message-polling.js +38 -19
  33. package/server/assets/chat/message-window.js +9 -5
  34. package/server/assets/chat/messages.js +53 -43
  35. package/server/assets/chat/palette.js +40 -26
  36. package/server/assets/chat/panels.js +0 -1
  37. package/server/assets/chat/pwa.js +5 -4
  38. package/server/assets/chat/questions.js +22 -20
  39. package/server/assets/chat/recall.js +39 -21
  40. package/server/assets/chat/receipts.js +9 -7
  41. package/server/assets/chat/reminders.js +22 -8
  42. package/server/assets/chat/replies.js +28 -12
  43. package/server/assets/chat/room-list.js +2 -2
  44. package/server/assets/chat/room-watcher.js +8 -4
  45. package/server/assets/chat/rooms.js +44 -36
  46. package/server/assets/chat/search.js +8 -6
  47. package/server/assets/chat/settings.js +12 -11
  48. package/server/assets/chat/shiki.js +1 -1
  49. package/server/assets/chat/shortcuts.js +0 -2
  50. package/server/assets/chat/side-pane.js +3 -2
  51. package/server/assets/chat/state.js +35 -26
  52. package/server/assets/chat/system-events.js +4 -4
  53. package/server/assets/chat/task-form.js +5 -5
  54. package/server/assets/chat/task-row.js +1 -1
  55. package/server/assets/chat/tasks.js +37 -25
  56. package/server/chat.html +1 -0
@@ -35,9 +35,9 @@ async function initializeMermaid() {
35
35
  const script = document.querySelector('script[src$="mermaid-11.12.2.min.js"]');
36
36
  if (!script)
37
37
  return reject(new Error("Mermaid bundle is missing"));
38
- script.addEventListener("load", resolve, { once: true });
38
+ script.addEventListener("load", () => resolve(), { once: true });
39
39
  script.addEventListener("error", reject, { once: true });
40
- window.addEventListener("load", resolve, { once: true });
40
+ window.addEventListener("load", () => resolve(), { once: true });
41
41
  });
42
42
  if (!window.mermaid)
43
43
  throw new Error("Mermaid bundle failed to load");
@@ -71,7 +71,7 @@ export async function renderDiagram(node, source, app) {
71
71
  throw new Error("Diagram SVG was rejected");
72
72
  // The intrinsic width stays in the viewBox; the message column scales it down.
73
73
  diagram.removeAttribute("style");
74
- const update = () => node.replaceChildren(fragment);
74
+ const update = async () => { node.replaceChildren(fragment); };
75
75
  if (app.preserveReadingLayout)
76
76
  await app.preserveReadingLayout(update);
77
77
  else
@@ -104,8 +104,6 @@ export function showDiagramFallback(node, source, app, loading) {
104
104
  node.append(pre);
105
105
  }
106
106
  }
107
- // The overlay shows a sanitized copy of the rendered SVG, so the thread keeps its
108
- // diagram and only the scale changes. A full-screen dialog keeps the thread in place.
109
107
  export function initDiagramViewer(app) {
110
108
  const dialog = app.$("#diagramViewer"), body = app.$("#diagramViewerBody"), stage = app.$("#diagramViewerStage");
111
109
  if (!dialog || !body || !stage)
@@ -208,15 +206,15 @@ export function initDiagramViewer(app) {
208
206
  }
209
207
  }
210
208
  function diagramSize(svg) {
211
- const box = svg.viewBox?.baseVal;
209
+ const box = svg instanceof SVGSVGElement ? svg.viewBox.baseVal : null;
212
210
  let width = box?.width || 0, height = box?.height || 0;
213
211
  if (!(width > 0) || !(height > 0)) {
214
- width = parseFloat(svg.getAttribute("width")) || 0;
215
- height = parseFloat(svg.getAttribute("height")) || 0;
212
+ width = parseFloat(svg.getAttribute("width") || "") || 0;
213
+ height = parseFloat(svg.getAttribute("height") || "") || 0;
216
214
  }
217
215
  return { width: width > 0 ? width : 640, height: height > 0 ? height : 420 };
218
216
  }
219
- const outside = (target) => target?.closest?.(".diagram-viewer-toolbar");
217
+ const outside = (target) => target instanceof Element && target.closest(".diagram-viewer-toolbar");
220
218
  // Only a press that began on the backdrop closes; a drag out of the canvas does not.
221
219
  let dismissPress = false;
222
220
  dialog.addEventListener("pointerdown", (event) => { dismissPress = event.target === dialog; });
@@ -1,5 +1,3 @@
1
- // Markdown resources open in a reading pane on wide screens, or in a modal overlay
2
- // when the window is too narrow or too short to give the chat a usable column.
3
1
  import { formatBytes, renderMarkdown } from "./markdown.js";
4
2
  import { docPreviewFormat, OFFICE_KINDS, OFFICE_PREVIEW_LIMIT, TEXT_PREVIEW_LIMIT } from "./resource-format.js";
5
3
  import { createCopyButton, copyResourceText } from "./copy-action.js";
@@ -43,14 +41,21 @@ export function initDocPreview(app) {
43
41
  const dialog = app.$("#docPreview");
44
42
  if (!dialog)
45
43
  return;
46
- const title = app.$("#docPreviewTitle"), size = app.$("#docPreviewSize");
47
- const status = app.$("#docPreviewStatus"), body = app.$("#docPreviewBody");
48
- const empty = app.$("#docPreviewEmpty"), download = app.$("#btnDocPreviewDownload");
49
- const languageLabel = app.$("#docPreviewLanguage"), notice = app.$("#docPreviewNotice");
50
- const eyebrow = app.$("#docPreviewEyebrow");
44
+ const $ = (selector) => {
45
+ const element = app.$(selector);
46
+ if (!element)
47
+ throw new Error(`Missing element: ${selector}`);
48
+ return element;
49
+ };
50
+ const title = $("#docPreviewTitle"), size = $("#docPreviewSize");
51
+ const status = $("#docPreviewStatus"), body = $("#docPreviewBody");
52
+ const empty = $("#docPreviewEmpty"), download = $("#btnDocPreviewDownload");
53
+ const languageLabel = $("#docPreviewLanguage"), notice = $("#docPreviewNotice");
54
+ const eyebrow = $("#docPreviewEyebrow");
51
55
  const fullscreenButton = app.$("#btnDocPreviewFullscreen");
52
- const chatView = app.$("#chatView"), pane = matchMedia(PANE_QUERY);
53
- let current = null, blob = null, objectUrl = null, token = 0, opener = null, openerResourceID = null, restoreOnClose = true;
56
+ const chatView = $("#chatView"), pane = matchMedia(PANE_QUERY);
57
+ let current = null, blob = null, objectUrl = null, token = 0;
58
+ let opener = null, openerResourceID = null, restoreOnClose = true;
54
59
  let rawText = "", fullscreen = false, paneMode = false;
55
60
  let officeKind = null, officeRender = 0, pptxWidth = 0, pptxTimer = 0;
56
61
  const copyButton = createCopyButton(app, "doc-preview-copy");
@@ -378,7 +383,7 @@ export function initDocPreview(app) {
378
383
  const active = document.activeElement;
379
384
  if (active && active !== document.body && active.id !== "msgInput")
380
385
  return;
381
- if (performance.now() < focusReplacement.until) {
386
+ if (performance.now() < (focusReplacement.until ?? 0)) {
382
387
  requestAnimationFrame(() => focusReplacement(resourceID, allowComposer));
383
388
  return;
384
389
  }
@@ -455,7 +460,9 @@ export function initDocPreview(app) {
455
460
  dismissPress = false;
456
461
  });
457
462
  const escapePreview = (event) => {
458
- if (!event || event.altKey || event.key !== "Escape" || !dialog.open)
463
+ const key = event && "key" in event && typeof event.key === "string" ? event.key : "";
464
+ const altKey = Boolean(event && "altKey" in event && event.altKey);
465
+ if (!event || altKey || key !== "Escape" || !dialog.open)
459
466
  return;
460
467
  event.preventDefault();
461
468
  event.stopPropagation();
@@ -2,7 +2,8 @@ import { createRandomId } from "./state.js";
2
2
  const trustedChipNames = new Map();
3
3
  const autoSeparator = "\uE000\uE001";
4
4
  function mentionName(node) {
5
- const name = trustedChipNames.get(node.dataset?.chatChip);
5
+ const chip = node.dataset.chatChip;
6
+ const name = chip === undefined ? undefined : trustedChipNames.get(chip);
6
7
  return name !== undefined && node.dataset.mention === name ? name : null;
7
8
  }
8
9
  function chipLabel(editor, name) {
@@ -14,26 +15,26 @@ export function editorText(editor, draft = false) {
14
15
  if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "DIV" && editor.firstElementChild?.nodeName === "BR")
15
16
  return "";
16
17
  let value = "";
17
- const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
18
+ const block = (node) => node.nodeName === "DIV";
18
19
  const walk = (node) => {
19
20
  if (node.nodeType === Node.TEXT_NODE)
20
- value += draft ? encodeDraftText(node.nodeValue) : node.nodeValue;
21
- else if (node.nodeType === Node.ELEMENT_NODE) {
22
- const mention = mentionName(node);
23
- if (node.dataset?.chatAutoSeparator)
24
- value += draft && node.textContent.startsWith(" ")
25
- ? autoSeparator + encodeDraftText(node.textContent.slice(1)) : draft ? encodeDraftText(node.textContent) : node.textContent;
21
+ value += draft ? encodeDraftText(node.nodeValue ?? "") : node.nodeValue ?? "";
22
+ else if (node instanceof HTMLElement) {
23
+ const mention = mentionName(node), text = node.textContent ?? "";
24
+ if (node.dataset.chatAutoSeparator)
25
+ value += draft && text.startsWith(" ")
26
+ ? autoSeparator + encodeDraftText(text.slice(1)) : draft ? encodeDraftText(text) : text;
26
27
  else if (mention !== null)
27
28
  value += `<at>@${mention}</at>`;
28
29
  else if (node.tagName === "BR") {
29
- if (!node.dataset?.chatTail)
30
+ if (!node.dataset.chatTail)
30
31
  value += "\n";
31
32
  }
32
33
  else
33
34
  node.childNodes.forEach((child, index, all) => {
34
35
  if (index && (block(child) || block(all[index - 1])))
35
36
  value += "\n";
36
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR"))
37
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
37
38
  walk(child);
38
39
  });
39
40
  }
@@ -41,7 +42,7 @@ export function editorText(editor, draft = false) {
41
42
  editor.childNodes.forEach((node, index, all) => {
42
43
  if (index && (block(node) || block(all[index - 1])))
43
44
  value += "\n";
44
- if (!(block(node) && node.childNodes.length === 1 && node.firstChild.nodeName === "BR"))
45
+ if (!(block(node) && node.childNodes.length === 1 && node.firstChild?.nodeName === "BR"))
45
46
  walk(node);
46
47
  });
47
48
  return value;
@@ -92,41 +93,51 @@ export function editorSelectionOffsets(editor) {
92
93
  return [editorText(editor).length, editorText(editor).length];
93
94
  const selected = selection.getRangeAt(0), collapsed = selected.collapsed;
94
95
  const offset = (node, position, isStart) => {
95
- const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
96
+ const element = node instanceof HTMLElement ? node : node.parentElement;
96
97
  const chip = element?.closest(".editor-mention");
97
98
  const raw = lengthBefore(editor, node, position);
98
- if (chip && editor.contains(chip) && mentionName(chip) !== null) {
99
- const start = lengthBefore(editor, chip, 0), end = start + `<at>@${mentionName(chip)}</at>`.length;
99
+ if (chip && editor.contains(chip)) {
100
+ const name = mentionName(chip);
100
101
  // A caret strictly inside a non-editable chip (e.g. left there by an
101
102
  // ESC-cancelled IME composition) is not a text position; snap to the end.
102
103
  // A selection edge inside a chip expands to the whole chip so copy and
103
104
  // cut keep the mention token instead of falling back to plain text.
104
- if (raw > start && raw < end)
105
- return collapsed || !isStart ? end : start;
105
+ if (name !== null) {
106
+ const start = lengthBefore(editor, chip, 0), end = start + `<at>@${name}</at>`.length;
107
+ if (raw > start && raw < end)
108
+ return collapsed || !isStart ? end : start;
109
+ }
106
110
  }
107
111
  return raw;
108
112
  };
109
113
  return [offset(selected.startContainer, selected.startOffset, true), offset(selected.endContainer, selected.endOffset, false)];
110
114
  }
111
115
  function lengthBefore(root, target, position) {
112
- const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
113
- const length = (node) => node.nodeType === Node.TEXT_NODE ? node.length
114
- : mentionName(node) !== null ? `<at>@${mentionName(node)}</at>`.length
115
- : node.tagName === "BR" ? (node.dataset?.chatTail ? 0 : 1) : childrenLength(node);
116
+ const block = (node) => node.nodeName === "DIV";
117
+ const length = (node) => {
118
+ if (node instanceof Text)
119
+ return node.length;
120
+ const mention = node instanceof HTMLElement ? mentionName(node) : null;
121
+ if (mention !== null)
122
+ return `<at>@${mention}</at>`.length;
123
+ if (node instanceof HTMLElement && node.tagName === "BR")
124
+ return node.dataset.chatTail ? 0 : 1;
125
+ return childrenLength(node);
126
+ };
116
127
  const childrenLength = (parent, until = parent.childNodes.length) => {
117
128
  let sum = 0;
118
129
  for (let index = 0; index < until; index++) {
119
130
  const child = parent.childNodes[index];
120
131
  if (index && (block(child) || block(parent.childNodes[index - 1])))
121
132
  sum++;
122
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR"))
133
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
123
134
  sum += length(child);
124
135
  }
125
136
  return sum;
126
137
  };
127
138
  const visit = (node) => {
128
139
  if (node === target)
129
- return node.nodeType === Node.TEXT_NODE ? Math.min(position, node.length)
140
+ return node instanceof Text ? Math.min(position, node.length)
130
141
  : childrenLength(node, position);
131
142
  let total = 0;
132
143
  for (let index = 0; index < node.childNodes.length; index++) {
@@ -135,7 +146,7 @@ function lengthBefore(root, target, position) {
135
146
  total++;
136
147
  if (child === target || child.contains(target))
137
148
  return total + visit(child);
138
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR"))
149
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
139
150
  total += length(child);
140
151
  }
141
152
  return total;
@@ -149,23 +160,23 @@ export function setCaret(editor, offset) {
149
160
  const [container, index] = textPoint(editorPoint(editor, offset));
150
161
  range.setStart(container, index);
151
162
  range.collapse(true);
152
- selection.removeAllRanges();
153
- selection.addRange(range);
163
+ selection?.removeAllRanges();
164
+ selection?.addRange(range);
154
165
  }
155
166
  function textPoint([container, offset]) {
156
167
  if (container.nodeType !== Node.ELEMENT_NODE)
157
168
  return [container, offset];
158
169
  const child = container.childNodes[offset], previous = container.childNodes[offset - 1];
159
- if (child?.nodeType === Node.TEXT_NODE && child.length === 0) {
170
+ if (child instanceof Text && child.length === 0) {
160
171
  const next = child.nextSibling;
161
- if (next?.nodeType === Node.TEXT_NODE) {
172
+ if (next instanceof Text) {
162
173
  child.remove();
163
174
  return [next, 0];
164
175
  }
165
176
  }
166
- if (child?.nodeType === Node.TEXT_NODE)
177
+ if (child instanceof Text)
167
178
  return [child, 0];
168
- if (previous?.nodeType === Node.TEXT_NODE)
179
+ if (previous instanceof Text)
169
180
  return [previous, previous.length];
170
181
  const text = document.createTextNode("");
171
182
  container.insertBefore(text, child || null);
@@ -176,8 +187,8 @@ export function setEditorSelection(editor, start, end = start) {
176
187
  const first = editorPoint(editor, start), last = editorPoint(editor, end);
177
188
  range.setStart(first[0], first[1]);
178
189
  range.setEnd(last[0], last[1]);
179
- selection.removeAllRanges();
180
- selection.addRange(range);
190
+ selection?.removeAllRanges();
191
+ selection?.addRange(range);
181
192
  }
182
193
  function editorPoint(editor, offset) {
183
194
  const atEnd = offset === editorText(editor).length;
@@ -188,36 +199,43 @@ function editorPoint(editor, offset) {
188
199
  const text = last.appendChild(document.createTextNode(""));
189
200
  return [text, 0];
190
201
  }
191
- if (atEnd && editor.lastChild?.nodeName === "BR") {
192
- if (!editor.lastChild.dataset?.chatTail) {
193
- const tail = document.createElement("br");
194
- tail.dataset.chatTail = "true";
195
- editor.append(tail);
202
+ const tail = editor.lastChild;
203
+ if (atEnd && tail instanceof HTMLElement && tail.nodeName === "BR") {
204
+ if (!tail.dataset.chatTail) {
205
+ const created = document.createElement("br");
206
+ created.dataset.chatTail = "true";
207
+ editor.append(created);
196
208
  }
197
209
  return [editor, editor.childNodes.length - 1];
198
210
  }
199
- const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
211
+ const block = (node) => node.nodeName === "DIV";
200
212
  let left = offset, point = null;
201
213
  const visit = (node) => {
202
214
  if (point)
203
215
  return;
204
- if (node.nodeType === Node.TEXT_NODE) {
216
+ if (node instanceof Text) {
205
217
  if (left <= node.length)
206
218
  point = [node, left];
207
219
  else
208
220
  left -= node.length;
209
221
  }
210
- else if (node.nodeType === Node.ELEMENT_NODE && mentionName(node) !== null) {
211
- const index = [...node.parentNode.childNodes].indexOf(node), length = `<at>@${mentionName(node)}</at>`.length;
222
+ else if (node instanceof HTMLElement && mentionName(node) !== null) {
223
+ const parent = node.parentNode;
224
+ if (!parent)
225
+ return;
226
+ const index = [...parent.childNodes].indexOf(node), length = `<at>@${mentionName(node)}</at>`.length;
212
227
  if (left <= length)
213
- point = [node.parentNode, index + (left ? 1 : 0)];
228
+ point = [parent, index + (left ? 1 : 0)];
214
229
  else
215
230
  left -= length;
216
231
  }
217
- else if (node.tagName === "BR") {
218
- const index = [...node.parentNode.childNodes].indexOf(node);
232
+ else if (node instanceof HTMLElement && node.tagName === "BR") {
233
+ const parent = node.parentNode;
234
+ if (!parent)
235
+ return;
236
+ const index = [...parent.childNodes].indexOf(node);
219
237
  if (left <= 1)
220
- point = [node.parentNode, index + (left ? 1 : 0)];
238
+ point = [parent, index + (left ? 1 : 0)];
221
239
  else
222
240
  left--;
223
241
  }
@@ -230,7 +248,7 @@ function editorPoint(editor, offset) {
230
248
  }
231
249
  left--;
232
250
  }
233
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR"))
251
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
234
252
  visit(child);
235
253
  });
236
254
  };
@@ -286,7 +304,7 @@ export function replaceEditorRange(editor, start, end, value, parseMentions = tr
286
304
  }
287
305
  function trimTrailingBreak(editor) {
288
306
  let last = editor.lastChild;
289
- if (last?.nodeName === "BR" && last.dataset?.chatTail)
307
+ if (last instanceof HTMLElement && last.nodeName === "BR" && last.dataset.chatTail)
290
308
  last = last.previousSibling;
291
309
  if (last?.nodeName === "BR")
292
310
  last.remove();
@@ -313,7 +331,8 @@ function knownMentions(editor, text) {
313
331
  // A copied mention only comes back if that name is still in the room.
314
332
  return text.replace(/<at>@([^<]+)<\/at>/g, (token, name) => editor.isKnownMention && !editor.isKnownMention(name) ? `@${name}` : token);
315
333
  }
316
- function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]); }
334
+ const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
335
+ function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => HTML_ESCAPES[char]); }
317
336
  function textHTML(text) { return escapeHTML(text).replace(/\r\n|\r|\n/g, "<br>"); }
318
337
  function createMention(editor, name) {
319
338
  const chip = document.createElement("span"), label = chipLabel(editor, name);
@@ -343,7 +362,7 @@ function wrapAutoSeparator(editor, offset) {
343
362
  function deleteMentionAtCaret(editor, event) {
344
363
  if (event.isComposing)
345
364
  return;
346
- const backward = event.inputType === "deleteContentBackward" || (event.key === "Backspace" && event.keyCode !== 229);
365
+ const backward = ("inputType" in event && event.inputType === "deleteContentBackward") || ("key" in event && event.key === "Backspace" && event.keyCode !== 229);
347
366
  if (!backward)
348
367
  return;
349
368
  const [caret, end] = editorSelectionOffsets(editor);
@@ -354,14 +373,16 @@ function deleteMentionAtCaret(editor, event) {
354
373
  const start = lengthBefore(editor, node, 0);
355
374
  return caret === start + 1 && node.previousElementSibling?.classList.contains("editor-mention");
356
375
  });
357
- const mention = separator?.previousElementSibling || chips.find((node) => {
376
+ const previous = separator?.previousElementSibling;
377
+ const mention = previous instanceof HTMLElement ? previous : chips.find((node) => {
358
378
  const start = lengthBefore(editor, node, 0);
359
379
  return caret > start && caret <= start + `<at>@${mentionName(node)}</at>`.length;
360
380
  });
361
381
  if (!mention)
362
382
  return;
363
383
  const start = lengthBefore(editor, mention, 0);
364
- const autoSeparator = mention.nextElementSibling?.dataset.chatAutoSeparator ? mention.nextElementSibling : null;
384
+ const next = mention.nextElementSibling;
385
+ const autoSeparator = next?.getAttribute("data-chat-auto-separator") ? next : null;
365
386
  event.preventDefault();
366
387
  mention.remove();
367
388
  autoSeparator?.remove();
@@ -385,9 +406,10 @@ export function installEditor(editor) {
385
406
  selectionStart: { get: () => editorSelectionOffsets(editor)[0] },
386
407
  selectionEnd: { get: () => editorSelectionOffsets(editor)[1] },
387
408
  });
388
- editor.getSelectionOffsets = () => editorSelectionOffsets(editor);
389
- editor.setCaret = (offset) => setCaret(editor, offset);
390
- editor.moveCaretToLineEdge = (end) => {
409
+ const control = editor;
410
+ control.getSelectionOffsets = () => editorSelectionOffsets(editor);
411
+ control.setCaret = (offset) => setCaret(editor, offset);
412
+ control.moveCaretToLineEdge = (end) => {
391
413
  const [start, finish] = editorSelectionOffsets(editor);
392
414
  const text = editorText(editor);
393
415
  const caret = end ? finish : start;
@@ -401,13 +423,13 @@ export function installEditor(editor) {
401
423
  const leading = !end ? text.slice(lineStart).match(/^(?:<at>@[^<]+<\/at>)+/) : null;
402
424
  setCaret(editor, leading ? lineStart + leading[0].length : target);
403
425
  };
404
- editor.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
405
- editor.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
426
+ control.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
427
+ control.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
406
428
  editor.addEventListener("input", pruneTrustedChipNames);
407
429
  editor.addEventListener("keydown", (event) => deleteMentionAtCaret(editor, event));
408
430
  editor.addEventListener("beforeinput", (event) => deleteMentionAtCaret(editor, event));
409
431
  editor.addEventListener("pointerdown", (event) => {
410
- const chip = event.target.closest?.(".editor-mention");
432
+ const chip = event.target instanceof Element ? event.target.closest(".editor-mention") : null;
411
433
  if (!chip || !editor.contains(chip))
412
434
  return;
413
435
  event.preventDefault();
@@ -464,8 +486,8 @@ export function installEditor(editor) {
464
486
  event.preventDefault();
465
487
  const range = document.caretRangeFromPoint?.(event.clientX, event.clientY), selection = getSelection();
466
488
  if (range && editor.contains(range.startContainer)) {
467
- selection.removeAllRanges();
468
- selection.addRange(range);
489
+ selection?.removeAllRanges();
490
+ selection?.addRange(range);
469
491
  }
470
492
  const [start, end] = editorSelectionOffsets(editor);
471
493
  const marked = html.includes("data-chatroom-mentions");
@@ -2,7 +2,8 @@ import { LS } from "./state.js";
2
2
  import { copyTextToClipboard } from "./markdown.js";
3
3
  import { followsBottom, pointerOrSelectionActive } from "./message-window.js";
4
4
  export function initEvents(app) {
5
- const $ = app.$;
5
+ // The chat shell owns these ids for the page lifetime.
6
+ const $ = (selector) => app.$(selector);
6
7
  // Thread clicks land on non-focusable nodes, so the browser drops focus to BODY
7
8
  // and the next keystroke is lost. Returning it to the composer matches chat UX.
8
9
  app.focusChatComposer = ({ force = false } = {}) => {
@@ -103,6 +104,7 @@ export function initEvents(app) {
103
104
  $("#restoreError").textContent = message;
104
105
  $("#restoreError").hidden = false;
105
106
  $("#btnRestoreRetry").hidden = false;
107
+ $("#btnRestoreSettings").hidden = false;
106
108
  };
107
109
  const roomRail = $("#roomRail"), drawerTrigger = $("#btnRoomsDrawer"), backdrop = $("#roomDrawerBackdrop");
108
110
  const smallScreen = () => matchMedia("(max-width: 760px)").matches;
@@ -114,17 +116,17 @@ export function initEvents(app) {
114
116
  readingPosition = { roomId: app.state.room?.id, messageId: anchor?.dataset.msgId, offset: anchor ? anchor.getBoundingClientRect().top - top : 0,
115
117
  atBottom: thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 80 };
116
118
  const guard = app.state.readAnchorGuard;
117
- let missing = Boolean(guard) && guard.roomId === readingPosition.roomId && Boolean(guard.missing);
119
+ let missing = Boolean(guard && guard.roomId === readingPosition.roomId && guard.missing);
118
120
  // A failed restore keeps its anchor while the landing stays put; scrolling to a
119
121
  // different message means the reader chose a new position and the old one is stale.
120
- if (missing) {
122
+ if (missing && guard) {
121
123
  if (!guard.landingId)
122
124
  guard.landingId = readingPosition.messageId;
123
125
  else if (readingPosition.messageId !== guard.landingId)
124
126
  missing = guard.missing = false;
125
127
  }
126
128
  if (readingPosition.roomId && anchor && (!missing || performance.now() <= app.state.userScrollIntentUntil)) {
127
- app.savePosition(readingPosition.roomId, { messageId: readingPosition.messageId, offset: readingPosition.offset, atBottom: readingPosition.atBottom });
129
+ app.savePosition(readingPosition.roomId, { messageId: readingPosition.messageId ?? "", offset: readingPosition.offset, atBottom: readingPosition.atBottom });
128
130
  }
129
131
  }
130
132
  app.captureReadingPosition = captureReadingPosition;
@@ -139,9 +141,9 @@ export function initEvents(app) {
139
141
  await new Promise((resolve) => requestAnimationFrame(resolve));
140
142
  if (roomId && app.state.room?.id === roomId && generation === scrollGeneration) {
141
143
  const thread = $("#thread");
142
- if (saved.atBottom && followsBottom(app))
144
+ if (saved?.atBottom && followsBottom(app))
143
145
  thread.scrollTop = thread.scrollHeight;
144
- else if (saved.messageId) {
146
+ else if (saved?.messageId) {
145
147
  const row = [...$("#msgList").querySelectorAll("[data-msg-id]")].find((item) => item.dataset.msgId === saved.messageId);
146
148
  if (row)
147
149
  thread.scrollTop += row.getBoundingClientRect().top - (thread.getBoundingClientRect().top + thread.clientTop + saved.offset);
@@ -263,7 +265,7 @@ export function initEvents(app) {
263
265
  (roomRail.querySelector('.room-row[aria-current="page"]') || $("#btnRefreshRooms")).focus();
264
266
  });
265
267
  backdrop.addEventListener("click", () => closeRoomDrawer());
266
- $("#roomListChat").addEventListener("click", (event) => { if (roomRail.classList.contains("drawer-open") && event.target.closest("[data-room-id]"))
268
+ $("#roomListChat").addEventListener("click", (event) => { if (roomRail.classList.contains("drawer-open") && event.target instanceof Element && event.target.closest("[data-room-id]"))
267
269
  closeRoomDrawer(); });
268
270
  const activateRoom = app.activateRoom;
269
271
  app.activateRoom = (id, preserveRoomListGeneration = false) => {
@@ -308,28 +310,32 @@ export function initEvents(app) {
308
310
  $("#restoreError").hidden = true;
309
311
  void app.refreshRoomList();
310
312
  });
313
+ // A cold start without network cannot restore a session, but local settings
314
+ // (theme, language, motion) must stay reachable from the cached shell.
315
+ $("#btnRestoreSettings").addEventListener("click", () => app.openSettings());
311
316
  $("#btnCancelToken").addEventListener("click", () => $("#tokenBox").close());
312
317
  $("#btnRefreshRooms").addEventListener("click", () => void app.refreshRoomList());
313
318
  $("#btnNewRoom").addEventListener("click", () => app.openCreateRoomDialog());
314
319
  $("#railRoomForm").addEventListener("submit", (event) => { event.preventDefault(); void app.createRoom(); });
315
- $("#inRoomNameChat").addEventListener("input", app.hideSendError);
320
+ // The original listener forwarded the event; a string never matches a stored error key.
321
+ $("#inRoomNameChat").addEventListener("input", (event) => app.hideSendError(String(event)));
316
322
  const input = $("#msgInput"), thread = $("#thread");
317
323
  const markScrollIntent = () => { scrollGeneration++; app.state.userScrollIntentUntil = performance.now() + 700; };
318
- window.addEventListener("resize", () => app.autoGrow(input));
324
+ window.addEventListener("resize", () => app.autoGrow?.(input));
319
325
  $(".composer").addEventListener("click", (event) => {
320
- const button = event.target.closest?.("[data-failed-action]");
326
+ const button = event.target instanceof Element ? event.target.closest("[data-failed-action]") : null;
321
327
  if (!button)
322
328
  return;
323
329
  const { failedAction, failedRoom, failedId } = button.dataset;
324
330
  if (failedAction === "retry")
325
- void app.retryFailedMessage(failedRoom, failedId);
331
+ void app.retryFailedMessage(failedRoom ?? "", failedId ?? "");
326
332
  else
327
- app.discardFailedMessage(failedRoom, failedId);
333
+ app.discardFailedMessage(failedRoom ?? "", failedId ?? "");
328
334
  });
329
335
  input.addEventListener("input", (event) => {
330
- app.autoGrow(input);
331
- app.updateSendState();
332
- app.updateDraftCount();
336
+ app.autoGrow?.(input);
337
+ app.updateSendState?.();
338
+ app.updateDraftCount?.();
333
339
  if (app.state.followBottom) {
334
340
  const thread = $("#thread");
335
341
  if (thread)
@@ -340,7 +346,7 @@ export function initEvents(app) {
340
346
  app.state.draftRevision.set(id, (app.state.draftRevision.get(id) || 0) + 1);
341
347
  app.saveDraft(id, input.draftValue);
342
348
  }
343
- if (!event.isComposing)
349
+ if (!(event instanceof InputEvent && event.isComposing))
344
350
  app.recomputeMention();
345
351
  });
346
352
  input.addEventListener("compositionend", () => {
@@ -379,14 +385,14 @@ export function initEvents(app) {
379
385
  if (app.mentionActive && /^(ArrowLeft|ArrowRight|Home|End)$/.test(event.key))
380
386
  app.recomputeMention();
381
387
  });
382
- input.addEventListener("click", app.recomputeMention);
388
+ input.addEventListener("click", () => app.recomputeMention());
383
389
  input.addEventListener("blur", () => app.closeMention());
384
390
  $("#mentionPicker").addEventListener("mousedown", (event) => {
385
- const option = event.target.closest(".mention-opt");
391
+ const option = event.target instanceof Element ? event.target.closest(".mention-opt") : null;
386
392
  if (!option)
387
393
  return;
388
394
  event.preventDefault();
389
- app.insertMention(option.dataset.name);
395
+ app.insertMention(option.dataset.name ?? "");
390
396
  });
391
397
  // Stop wheel overscroll at the ends. Without this, some layouts let the
392
398
  // document absorb the leftover delta and the view jumps a few pixels.
@@ -441,9 +447,9 @@ export function initEvents(app) {
441
447
  captureReadingPosition();
442
448
  if (!adjusting && thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80)
443
449
  void app.markActiveRoomRead(performance.now() <= app.state.userScrollIntentUntil);
444
- app.queueReceiptRefresh();
450
+ app.queueReceiptRefresh?.();
445
451
  if (!adjusting)
446
- app.queueReceiptObservation();
452
+ app.queueReceiptObservation?.();
447
453
  app.updateJump();
448
454
  if (!adjusting && !app.state.jumpToLoadedTop && thread.scrollTop < 160)
449
455
  void app.loadOlderHistory?.();
@@ -458,14 +464,14 @@ export function initEvents(app) {
458
464
  window.addEventListener("focus", () => {
459
465
  if (!app.state.resizeScrollAdjusting && !app.state.layoutScrollAdjusting) {
460
466
  void app.markActiveRoomRead();
461
- app.queueReceiptObservation();
467
+ app.queueReceiptObservation?.();
462
468
  }
463
- app.queueReceiptRefresh();
469
+ app.queueReceiptRefresh?.();
464
470
  });
465
471
  $("#msgList").addEventListener("click", (event) => {
466
- const messageButton = event.target.closest("[data-copy-message]");
472
+ const messageButton = event.target instanceof Element ? event.target.closest("[data-copy-message]") : null;
467
473
  if (messageButton)
468
- void copyTextToClipboard(messageButton._copyText, true).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
474
+ void copyTextToClipboard(messageButton._copyText ?? "", true).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
469
475
  });
470
476
  document.addEventListener("copy", (event) => {
471
477
  // A plain browser copy of rendered mentions loses their tokens. Rebuild them
@@ -493,7 +499,8 @@ export function initEvents(app) {
493
499
  return;
494
500
  selectedChips.forEach((chip) => chip.replaceWith(document.createTextNode(`<at>@${chip.dataset.mention ?? chip.textContent?.slice(1) ?? ""}</at>`)));
495
501
  const text = fragment.textContent ?? "";
496
- const html = `<div data-chatroom-mentions>${text.replace(/[&<>"]/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[char])}</div>`;
502
+ const escapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
503
+ const html = `<div data-chatroom-mentions>${text.replace(/[&<>"]/g, (char) => escapes[char])}</div>`;
497
504
  event.clipboardData?.setData("text/plain", text);
498
505
  event.clipboardData?.setData("text/html", html);
499
506
  event.preventDefault();
@@ -505,7 +512,7 @@ export function initEvents(app) {
505
512
  $(selector).addEventListener("keydown", (event) => {
506
513
  if (event.key === "Enter") {
507
514
  event.preventDefault();
508
- document.querySelector(`[data-token-save="${selector.slice(1)}"]`).click();
515
+ document.querySelector(`[data-token-save="${selector.slice(1)}"]`)?.click();
509
516
  }
510
517
  });
511
518
  $(selector).addEventListener("input", () => {
@@ -589,6 +596,8 @@ export function initEvents(app) {
589
596
  event.preventDefault();
590
597
  const step = event.key === "ArrowDown" ? 1 : -1;
591
598
  const nextRoom = joined[(index + step + joined.length) % joined.length];
599
+ if (!nextRoom)
600
+ return;
592
601
  if (app.switchRoom)
593
602
  app.switchRoom(nextRoom.id, step);
594
603
  else {
@@ -605,10 +614,14 @@ export function initEvents(app) {
605
614
  $("#inRoomId").focus();
606
615
  }
607
616
  function saveAccessToken(button, app) {
608
- const input = document.getElementById(button.dataset.tokenSave);
617
+ const input = document.getElementById(button.dataset.tokenSave ?? "");
609
618
  input.value = app.setToken(input.value);
610
- document.querySelector("#inToken").value = LS.token;
611
- document.querySelector("#inTokenChat").value = LS.token;
619
+ const token = document.querySelector("#inToken");
620
+ const chatToken = document.querySelector("#inTokenChat");
621
+ if (token)
622
+ token.value = LS.token;
623
+ if (chatToken)
624
+ chatToken.value = LS.token;
612
625
  let persistent = false;
613
626
  try {
614
627
  persistent = localStorage.getItem("chat.token") === LS.token;