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

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 (156) hide show
  1. package/CHANGELOG.md +7 -1
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/cli.ts +1 -1
  5. package/dist/cli.js +35 -16
  6. package/package.json +15 -9
  7. package/packages/chat-room-channeld/README.md +3 -2
  8. package/packages/chat-room-channeld/src/inbound.ts +3 -6
  9. package/packages/chat-room-channeld/src/pg/sql.mjs +157 -142
  10. package/packages/chat-room-channeld/src/pg/sql.mts +175 -0
  11. package/packages/chat-room-channeld/src/pg/worker.mjs +107 -99
  12. package/packages/chat-room-channeld/src/pg/worker.mts +166 -0
  13. package/plugin.ts +1 -1
  14. package/server/assets/chat/admin-badge.js +1 -1
  15. package/server/assets/chat/admin.js +16 -10
  16. package/server/assets/chat/announcements.js +12 -2
  17. package/server/assets/chat/attachment-store.js +15 -6
  18. package/server/assets/chat/attachments.js +48 -33
  19. package/server/assets/chat/chat-background.js +8 -14
  20. package/server/assets/chat/clipboard.js +2 -1
  21. package/server/assets/chat/confirm-dialog.js +3 -3
  22. package/server/assets/chat/copy-action.js +1 -2
  23. package/server/assets/chat/diagram-viewer.js +7 -9
  24. package/server/assets/chat/doc-preview.js +19 -12
  25. package/server/assets/chat/editor.js +87 -61
  26. package/server/assets/chat/events.js +49 -34
  27. package/server/assets/chat/files.js +45 -13
  28. package/server/assets/chat/history-loader.js +5 -3
  29. package/server/assets/chat/image-zoom.js +21 -17
  30. package/server/assets/chat/install-prompt.js +10 -9
  31. package/server/assets/chat/integration-account-schema.js +5 -3
  32. package/server/assets/chat/integration-editor.js +2 -2
  33. package/server/assets/chat/integration-values.js +17 -11
  34. package/server/assets/chat/integrations.js +138 -81
  35. package/server/assets/chat/join-requests.js +20 -13
  36. package/server/assets/chat/markdown-footnotes.js +8 -8
  37. package/server/assets/chat/markdown.js +48 -38
  38. package/server/assets/chat/members.js +48 -25
  39. package/server/assets/chat/mentions.js +39 -12
  40. package/server/assets/chat/message-cache.js +2 -2
  41. package/server/assets/chat/message-polling.js +40 -21
  42. package/server/assets/chat/message-window.js +10 -6
  43. package/server/assets/chat/messages.js +70 -46
  44. package/server/assets/chat/office-preview.js +3 -3
  45. package/server/assets/chat/palette.js +45 -29
  46. package/server/assets/chat/panels.js +19 -1
  47. package/server/assets/chat/pwa.js +5 -4
  48. package/server/assets/chat/questions.js +25 -22
  49. package/server/assets/chat/recall.js +39 -21
  50. package/server/assets/chat/receipts.js +9 -7
  51. package/server/assets/chat/reminders.js +25 -8
  52. package/server/assets/chat/replies.js +34 -15
  53. package/server/assets/chat/resource-format.js +2 -2
  54. package/server/assets/chat/room-list.js +2 -2
  55. package/server/assets/chat/room-watcher.js +8 -4
  56. package/server/assets/chat/rooms.js +51 -40
  57. package/server/assets/chat/search.js +8 -6
  58. package/server/assets/chat/settings.js +16 -14
  59. package/server/assets/chat/shiki.js +1 -1
  60. package/server/assets/chat/shortcuts.js +3 -3
  61. package/server/assets/chat/side-pane.js +4 -3
  62. package/server/assets/chat/state.js +65 -37
  63. package/server/assets/chat/system-events.js +6 -5
  64. package/server/assets/chat/system-messages.js +15 -15
  65. package/server/assets/chat/task-form.js +5 -5
  66. package/server/assets/chat/task-row.js +1 -1
  67. package/server/assets/chat/tasks.js +41 -28
  68. package/server/assets/chat/window-controls.js +3 -2
  69. package/server/assets/conversation.css +14 -2
  70. package/server/assets/doc-preview.css +6 -0
  71. package/server/assets/office/THIRD-PARTY-NOTICES.txt +23 -1
  72. package/server/assets/office/licenses/docx-preview-HEADER.txt +6 -0
  73. package/server/assets/office/licenses/echarts-LICENSE-d3.txt +27 -0
  74. package/server/assets/office/licenses/echarts-NOTICE.txt +5 -0
  75. package/server/assets/office/licenses/immediate-LICENSE.txt +20 -0
  76. package/server/assets/office/licenses/lie-LICENSE.txt +7 -0
  77. package/server/assets/office/licenses/pako-LICENSE.txt +21 -0
  78. package/server/assets/office/licenses/pako-ZLIB.txt +18 -0
  79. package/server/assets/office/licenses/setimmediate-LICENSE.txt +20 -0
  80. package/server/chat.html +1 -0
  81. package/server/sw.js +3 -1
  82. package/skills/chatroom/SKILL.md +9 -0
  83. package/src/README.md +1 -1
  84. package/src/agent/agent-receipts.ts +12 -4
  85. package/src/center/center-client.ts +1 -1
  86. package/src/state/pg-sql.mjs +157 -142
  87. package/src/state/pg-sql.mts +175 -0
  88. package/src/state/pg-worker.mjs +107 -99
  89. package/src/state/pg-worker.mts +166 -0
  90. package/src/state/store.ts +21 -7
  91. package/src/tui/app-types.mjs +1 -0
  92. package/src/tui/app-types.mts +175 -0
  93. package/src/tui/app.mjs +426 -423
  94. package/src/tui/app.mts +500 -0
  95. package/src/tui/config.mjs +166 -158
  96. package/src/tui/config.mts +247 -0
  97. package/src/tui/http.mjs +239 -206
  98. package/src/tui/http.mts +412 -0
  99. package/src/tui/i18n.mjs +17 -20
  100. package/src/tui/i18n.mts +42 -0
  101. package/src/tui/info-app.mjs +431 -427
  102. package/src/tui/info-app.mts +500 -0
  103. package/src/tui/info-content.mjs +205 -199
  104. package/src/tui/info-content.mts +341 -0
  105. package/src/tui/join-app.mjs +75 -64
  106. package/src/tui/join-app.mts +99 -0
  107. package/src/tui/locales/en.mjs +302 -320
  108. package/src/tui/locales/en.mts +349 -0
  109. package/src/tui/locales/zh-CN.mjs +302 -320
  110. package/src/tui/locales/zh-CN.mts +349 -0
  111. package/src/tui/main.mjs +219 -213
  112. package/src/tui/main.mts +255 -0
  113. package/src/tui/markdown.mjs +128 -272
  114. package/src/tui/markdown.mts +152 -0
  115. package/src/tui/mentions.mjs +181 -184
  116. package/src/tui/mentions.mts +251 -0
  117. package/src/tui/message-app.mjs +181 -173
  118. package/src/tui/message-app.mts +213 -0
  119. package/src/tui/message-view.mjs +90 -111
  120. package/src/tui/message-view.mts +151 -0
  121. package/src/tui/messages.mjs +55 -49
  122. package/src/tui/messages.mts +106 -0
  123. package/src/tui/palette-app.mjs +364 -344
  124. package/src/tui/palette-app.mts +388 -0
  125. package/src/tui/palette.mjs +100 -98
  126. package/src/tui/palette.mts +176 -0
  127. package/src/tui/prefs.mjs +56 -63
  128. package/src/tui/prefs.mts +126 -0
  129. package/src/tui/reminder-app.mjs +191 -181
  130. package/src/tui/reminder-app.mts +228 -0
  131. package/src/tui/room-settings-app.mjs +257 -242
  132. package/src/tui/room-settings-app.mts +301 -0
  133. package/src/tui/session.mjs +30 -29
  134. package/src/tui/session.mts +51 -0
  135. package/src/tui/settings-app.mjs +151 -138
  136. package/src/tui/settings-app.mts +179 -0
  137. package/src/tui/ui-content.mjs +426 -421
  138. package/src/tui/ui-content.mts +499 -0
  139. package/src/tui/ui-help.mjs +58 -67
  140. package/src/tui/ui-help.mts +87 -0
  141. package/src/tui/ui-mentions.mjs +34 -36
  142. package/src/tui/ui-mentions.mts +60 -0
  143. package/src/tui/ui-overlay-view.mjs +259 -267
  144. package/src/tui/ui-overlay-view.mts +322 -0
  145. package/src/tui/ui-suggest-view.mjs +54 -57
  146. package/src/tui/ui-suggest-view.mts +78 -0
  147. package/src/tui/ui-suggest.mjs +164 -167
  148. package/src/tui/ui-suggest.mts +248 -0
  149. package/src/tui/ui-theme.mjs +52 -57
  150. package/src/tui/ui-theme.mts +98 -0
  151. package/src/tui/ui-view.mjs +267 -275
  152. package/src/tui/ui-view.mts +308 -0
  153. package/src/tui/ui.mjs +372 -359
  154. package/src/tui/ui.mts +440 -0
  155. package/src/tui/wire.mjs +215 -0
  156. package/src/tui/wire.mts +383 -0
@@ -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;
@@ -79,7 +80,7 @@ export function setEditorText(editor, value, draft = false) {
79
80
  offset = pattern.lastIndex;
80
81
  continue;
81
82
  }
82
- editor.append(createMention(editor, draft ? match[2] : match[1]));
83
+ editor.append(createMention(editor, (draft ? match[2] : match[1]) ?? ""));
83
84
  offset = pattern.lastIndex;
84
85
  }
85
86
  appendText(editor, String(value).slice(offset));
@@ -92,50 +93,64 @@ 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];
131
+ if (!child)
132
+ break;
120
133
  if (index && (block(child) || block(parent.childNodes[index - 1])))
121
134
  sum++;
122
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR"))
135
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
123
136
  sum += length(child);
124
137
  }
125
138
  return sum;
126
139
  };
127
140
  const visit = (node) => {
128
141
  if (node === target)
129
- return node.nodeType === Node.TEXT_NODE ? Math.min(position, node.length)
142
+ return node instanceof Text ? Math.min(position, node.length)
130
143
  : childrenLength(node, position);
131
144
  let total = 0;
132
145
  for (let index = 0; index < node.childNodes.length; index++) {
133
146
  const child = node.childNodes[index];
147
+ if (!child)
148
+ break;
134
149
  if (index && (block(child) || block(node.childNodes[index - 1])))
135
150
  total++;
136
151
  if (child === target || child.contains(target))
137
152
  return total + visit(child);
138
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR"))
153
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
139
154
  total += length(child);
140
155
  }
141
156
  return total;
@@ -149,23 +164,23 @@ export function setCaret(editor, offset) {
149
164
  const [container, index] = textPoint(editorPoint(editor, offset));
150
165
  range.setStart(container, index);
151
166
  range.collapse(true);
152
- selection.removeAllRanges();
153
- selection.addRange(range);
167
+ selection?.removeAllRanges();
168
+ selection?.addRange(range);
154
169
  }
155
170
  function textPoint([container, offset]) {
156
171
  if (container.nodeType !== Node.ELEMENT_NODE)
157
172
  return [container, offset];
158
173
  const child = container.childNodes[offset], previous = container.childNodes[offset - 1];
159
- if (child?.nodeType === Node.TEXT_NODE && child.length === 0) {
174
+ if (child instanceof Text && child.length === 0) {
160
175
  const next = child.nextSibling;
161
- if (next?.nodeType === Node.TEXT_NODE) {
176
+ if (next instanceof Text) {
162
177
  child.remove();
163
178
  return [next, 0];
164
179
  }
165
180
  }
166
- if (child?.nodeType === Node.TEXT_NODE)
181
+ if (child instanceof Text)
167
182
  return [child, 0];
168
- if (previous?.nodeType === Node.TEXT_NODE)
183
+ if (previous instanceof Text)
169
184
  return [previous, previous.length];
170
185
  const text = document.createTextNode("");
171
186
  container.insertBefore(text, child || null);
@@ -176,8 +191,8 @@ export function setEditorSelection(editor, start, end = start) {
176
191
  const first = editorPoint(editor, start), last = editorPoint(editor, end);
177
192
  range.setStart(first[0], first[1]);
178
193
  range.setEnd(last[0], last[1]);
179
- selection.removeAllRanges();
180
- selection.addRange(range);
194
+ selection?.removeAllRanges();
195
+ selection?.addRange(range);
181
196
  }
182
197
  function editorPoint(editor, offset) {
183
198
  const atEnd = offset === editorText(editor).length;
@@ -188,36 +203,43 @@ function editorPoint(editor, offset) {
188
203
  const text = last.appendChild(document.createTextNode(""));
189
204
  return [text, 0];
190
205
  }
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);
206
+ const tail = editor.lastChild;
207
+ if (atEnd && tail instanceof HTMLElement && tail.nodeName === "BR") {
208
+ if (!tail.dataset.chatTail) {
209
+ const created = document.createElement("br");
210
+ created.dataset.chatTail = "true";
211
+ editor.append(created);
196
212
  }
197
213
  return [editor, editor.childNodes.length - 1];
198
214
  }
199
- const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
215
+ const block = (node) => node?.nodeName === "DIV";
200
216
  let left = offset, point = null;
201
217
  const visit = (node) => {
202
218
  if (point)
203
219
  return;
204
- if (node.nodeType === Node.TEXT_NODE) {
220
+ if (node instanceof Text) {
205
221
  if (left <= node.length)
206
222
  point = [node, left];
207
223
  else
208
224
  left -= node.length;
209
225
  }
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;
226
+ else if (node instanceof HTMLElement && mentionName(node) !== null) {
227
+ const parent = node.parentNode;
228
+ if (!parent)
229
+ return;
230
+ const index = [...parent.childNodes].indexOf(node), length = `<at>@${mentionName(node)}</at>`.length;
212
231
  if (left <= length)
213
- point = [node.parentNode, index + (left ? 1 : 0)];
232
+ point = [parent, index + (left ? 1 : 0)];
214
233
  else
215
234
  left -= length;
216
235
  }
217
- else if (node.tagName === "BR") {
218
- const index = [...node.parentNode.childNodes].indexOf(node);
236
+ else if (node instanceof HTMLElement && node.tagName === "BR") {
237
+ const parent = node.parentNode;
238
+ if (!parent)
239
+ return;
240
+ const index = [...parent.childNodes].indexOf(node);
219
241
  if (left <= 1)
220
- point = [node.parentNode, index + (left ? 1 : 0)];
242
+ point = [parent, index + (left ? 1 : 0)];
221
243
  else
222
244
  left--;
223
245
  }
@@ -230,7 +252,7 @@ function editorPoint(editor, offset) {
230
252
  }
231
253
  left--;
232
254
  }
233
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR"))
255
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
234
256
  visit(child);
235
257
  });
236
258
  };
@@ -255,9 +277,9 @@ export function replaceEditorRange(editor, start, end, value, parseMentions = tr
255
277
  let html = "", cursor = 0, match;
256
278
  while (token && (match = token.exec(content))) {
257
279
  html += textHTML(content.slice(cursor, match.index));
258
- const name = escapeHTML(match[1]), label = escapeHTML(chipLabel(editor, match[1]));
280
+ const mention = match[1] ?? "", name = escapeHTML(mention), label = escapeHTML(chipLabel(editor, mention));
259
281
  const chipID = createRandomId();
260
- trustedChipNames.set(chipID, match[1]);
282
+ trustedChipNames.set(chipID, mention);
261
283
  html += `<span class="editor-mention" data-mention="${name}" data-chat-chip="${chipID}" data-insert-marker="${marker}" contenteditable="false" role="img" aria-label="Mention ${label}">@${label}</span>`;
262
284
  cursor = token.lastIndex;
263
285
  }
@@ -286,7 +308,7 @@ export function replaceEditorRange(editor, start, end, value, parseMentions = tr
286
308
  }
287
309
  function trimTrailingBreak(editor) {
288
310
  let last = editor.lastChild;
289
- if (last?.nodeName === "BR" && last.dataset?.chatTail)
311
+ if (last instanceof HTMLElement && last.nodeName === "BR" && last.dataset.chatTail)
290
312
  last = last.previousSibling;
291
313
  if (last?.nodeName === "BR")
292
314
  last.remove();
@@ -313,7 +335,8 @@ function knownMentions(editor, text) {
313
335
  // A copied mention only comes back if that name is still in the room.
314
336
  return text.replace(/<at>@([^<]+)<\/at>/g, (token, name) => editor.isKnownMention && !editor.isKnownMention(name) ? `@${name}` : token);
315
337
  }
316
- function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]); }
338
+ const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
339
+ function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char); }
317
340
  function textHTML(text) { return escapeHTML(text).replace(/\r\n|\r|\n/g, "<br>"); }
318
341
  function createMention(editor, name) {
319
342
  const chip = document.createElement("span"), label = chipLabel(editor, name);
@@ -343,7 +366,7 @@ function wrapAutoSeparator(editor, offset) {
343
366
  function deleteMentionAtCaret(editor, event) {
344
367
  if (event.isComposing)
345
368
  return;
346
- const backward = event.inputType === "deleteContentBackward" || (event.key === "Backspace" && event.keyCode !== 229);
369
+ const backward = ("inputType" in event && event.inputType === "deleteContentBackward") || ("key" in event && event.key === "Backspace" && event.keyCode !== 229);
347
370
  if (!backward)
348
371
  return;
349
372
  const [caret, end] = editorSelectionOffsets(editor);
@@ -354,14 +377,16 @@ function deleteMentionAtCaret(editor, event) {
354
377
  const start = lengthBefore(editor, node, 0);
355
378
  return caret === start + 1 && node.previousElementSibling?.classList.contains("editor-mention");
356
379
  });
357
- const mention = separator?.previousElementSibling || chips.find((node) => {
380
+ const previous = separator?.previousElementSibling;
381
+ const mention = previous instanceof HTMLElement ? previous : chips.find((node) => {
358
382
  const start = lengthBefore(editor, node, 0);
359
383
  return caret > start && caret <= start + `<at>@${mentionName(node)}</at>`.length;
360
384
  });
361
385
  if (!mention)
362
386
  return;
363
387
  const start = lengthBefore(editor, mention, 0);
364
- const autoSeparator = mention.nextElementSibling?.dataset.chatAutoSeparator ? mention.nextElementSibling : null;
388
+ const next = mention.nextElementSibling;
389
+ const autoSeparator = next?.getAttribute("data-chat-auto-separator") ? next : null;
365
390
  event.preventDefault();
366
391
  mention.remove();
367
392
  autoSeparator?.remove();
@@ -385,9 +410,10 @@ export function installEditor(editor) {
385
410
  selectionStart: { get: () => editorSelectionOffsets(editor)[0] },
386
411
  selectionEnd: { get: () => editorSelectionOffsets(editor)[1] },
387
412
  });
388
- editor.getSelectionOffsets = () => editorSelectionOffsets(editor);
389
- editor.setCaret = (offset) => setCaret(editor, offset);
390
- editor.moveCaretToLineEdge = (end) => {
413
+ const control = editor;
414
+ control.getSelectionOffsets = () => editorSelectionOffsets(editor);
415
+ control.setCaret = (offset) => setCaret(editor, offset);
416
+ control.moveCaretToLineEdge = (end) => {
391
417
  const [start, finish] = editorSelectionOffsets(editor);
392
418
  const text = editorText(editor);
393
419
  const caret = end ? finish : start;
@@ -401,13 +427,13 @@ export function installEditor(editor) {
401
427
  const leading = !end ? text.slice(lineStart).match(/^(?:<at>@[^<]+<\/at>)+/) : null;
402
428
  setCaret(editor, leading ? lineStart + leading[0].length : target);
403
429
  };
404
- editor.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
405
- editor.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
430
+ control.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
431
+ control.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
406
432
  editor.addEventListener("input", pruneTrustedChipNames);
407
433
  editor.addEventListener("keydown", (event) => deleteMentionAtCaret(editor, event));
408
434
  editor.addEventListener("beforeinput", (event) => deleteMentionAtCaret(editor, event));
409
435
  editor.addEventListener("pointerdown", (event) => {
410
- const chip = event.target.closest?.(".editor-mention");
436
+ const chip = event.target instanceof Element ? event.target.closest(".editor-mention") : null;
411
437
  if (!chip || !editor.contains(chip))
412
438
  return;
413
439
  event.preventDefault();
@@ -464,8 +490,8 @@ export function installEditor(editor) {
464
490
  event.preventDefault();
465
491
  const range = document.caretRangeFromPoint?.(event.clientX, event.clientY), selection = getSelection();
466
492
  if (range && editor.contains(range.startContainer)) {
467
- selection.removeAllRanges();
468
- selection.addRange(range);
493
+ selection?.removeAllRanges();
494
+ selection?.addRange(range);
469
495
  }
470
496
  const [start, end] = editorSelectionOffsets(editor);
471
497
  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);
@@ -186,7 +188,7 @@ export function initEvents(app) {
186
188
  backdrop.hidden = true;
187
189
  return;
188
190
  }
189
- backdropTimer = setTimeout(() => { backdrop.hidden = true; }, 200);
191
+ backdropTimer = window.setTimeout(() => { backdrop.hidden = true; }, 200);
190
192
  }
191
193
  function syncRoomDrawer() {
192
194
  // Crossing the drawer breakpoint jumps straight to the target layout instead
@@ -196,7 +198,7 @@ export function initEvents(app) {
196
198
  drawerWasSmall = small;
197
199
  roomRail.classList.add("no-drawer-animation");
198
200
  clearTimeout(drawerAnimationTimer);
199
- drawerAnimationTimer = setTimeout(() => roomRail.classList.remove("no-drawer-animation"), 260);
201
+ drawerAnimationTimer = window.setTimeout(() => roomRail.classList.remove("no-drawer-animation"), 260);
200
202
  }
201
203
  if (!small) {
202
204
  roomRail.classList.remove("drawer-open");
@@ -223,7 +225,7 @@ export function initEvents(app) {
223
225
  app.state.receiptObservationFrame = 0;
224
226
  app.state.receiptObservation = null;
225
227
  clearTimeout(resizeResetTimer);
226
- resizeResetTimer = setTimeout(() => { if (generation === resizeGeneration)
228
+ resizeResetTimer = window.setTimeout(() => { if (generation === resizeGeneration)
227
229
  app.state.resizeScrollAdjusting = false; }, 500);
228
230
  if (resizeFrame)
229
231
  cancelAnimationFrame(resizeFrame);
@@ -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] ?? 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;
@@ -650,7 +663,9 @@ function handleMessageKey(event, app) {
650
663
  if (event.key === "Enter" || event.key === "Tab") {
651
664
  if (app.mention?.items.length) {
652
665
  event.preventDefault();
653
- app.insertMention(app.mention.items[app.mention.index]);
666
+ const item = app.mention.items[app.mention.index];
667
+ if (item)
668
+ app.insertMention(item);
654
669
  return;
655
670
  }
656
671
  app.closeMention();